From: Gerd Stolpmann <Gerd.Stolpmann@darmstadt.netsurf.de>
To: caml-list@inria.fr
Subject: Re: one-time initialization
Date: Thu, 28 Jan 1999 21:23:21 +0100
Message-Id: <99012821410500.10116@schneemann>
On Thu, 28 Jan 1999, Michael Hicks wrote:
>I wonder if anyone knows how to optimize the following (simplified for the
>sake of dicussion) situation:
>
>let global = ref None
>let init i =
> global := Some i
>let f () =
> match (!global) with
> Some x -> x
> | None -> failwith "not initialized";;
>let g() =
> match (!global) with
> ...
>
>Essentially, there is some global state that is initialized once, and is
>used by all functions in the module. In a more realistic situation, this
>state might be initialized by reading in a file. Given that following
>initialization the global state never changes, it should be conceivable to
>eliminate the match and dereference; on my machine (pentium 166), the match
>and dereference result in about a 30% slowdown. I've fooled around with
>some things, but haven't found anything that performs better than this
>straightforward approach or is any more elegant.
If you encapsulate your module, there is a solution that may eliminate
the need of an 'option' type
(I assume that 'global' has type t ref, and that v is a known value of t):
module M :
sig
type initialized
val init : t -> initialized
val f : initialized -> t
val g : initialized -> ...
end =
struct
type initialized = unit
let global = ref v
let init i = global := i
let f () = !global
let g () = ...
end
You can only call f and g if you have a value of type 'initialized', and your
only chance to get it is to call 'init'. This is a good example how to use
types as assertions about state. This simply means that the type checker prooves
for you that f and g are never called before init.
To get rid of dereferencing is impossible. Perhaps a mutable
record is faster in some cases.
-- ---------------------------------------------------------------------------- Gerd Stolpmann Telefon: +49 6151 997705 (privat) Viktoriastr. 100 64293 Darmstadt EMail: Gerd.Stolpmann@darmstadt.netsurf.de (privat) Germany ----------------------------------------------------------------------------
This archive was generated by hypermail 2b29 : Sun Jan 02 2000 - 11:58:19 MET