Re: [caml] Closures and efficiency

From: Francois Pottier (
Date: Fri Oct 29 1999 - 11:39:18 MET DST

Date: Fri, 29 Oct 1999 11:39:18 +0200
From: Francois Pottier <>
To: Christopher Jeris <>
Subject: Re: [caml] Closures and efficiency
In-Reply-To: <>; from Christopher Jeris on Tue, Oct 26, 1999 at 06:06:28PM -0400


> Here's the nub of my question. In a typical synth architecture there are
> very many parameters which take values 0..127. If I had a function
> int_subrange_encoder: int -> int -> param_value -> bytestring
> which took the bounds of a subrange and generated an encoder function for
> values of that subrange, and then in a voice-architecture description I
> had a list of very many records each of which contained an entry
> int_subrange_encoder 0 127
> would I suddenly have six million little closures, or would the compiler
> do common-subexpression elimination on them ?

I don't know if the compiler performs CSE for expressions which involve
function applications (it would have to prove that the function
int_subrange_encoder does not perform side effects, which I think
it doesn't -- but I could be wrong).

However, if you're worried by memory consumption, you can easily create
a memoizing version of int_subrange_encoder. Here is a generic "memoize"
function which accepts any 1-parameter function f and returns a
memoizing version of it. (You can adapt it for 2 arguments if you wish,
or uncurry the function int_subrange_encoder, as I have done below.)

  let memoize f =
    let table = Hashtbl.create 1023 in
    fun argument ->
        Hashtbl.find table argument
      with Not_found ->
        let result = f argument in
        Hashtbl.add table argument result;

Of course, memoizing a function f only makes sense if it is applicative,
i.e. it returns the same result when applied twice, and it performs no
observable side effects. You can write:

  let int_subrange_encoder (x, y) =

  let memoized_int_subrange_encoder =
    memoize int_subrange_encoder

Hope this helps,

François Pottier

This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:28 MET