English version
Accueil     À propos     Téléchargement     Ressources     Contactez-nous    

Ce site est rarement mis à jour. Pour les informations les plus récentes, rendez-vous sur le nouveau site OCaml à l'adresse ocaml.org.

Browse thread
[caml] Closures and efficiency
[ Home ] [ Index: by date | by threads ]
[ Search: ]

[ Message by date: previous | next ] [ Message in thread: previous | next ] [ Thread: previous | next ]
Date: 1999-10-29 (17:21)
From: Francois Pottier <Francois.Pottier@i...>
Subject: Re: [caml] Closures and efficiency


> 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