one-time initialization

From: Adam P. Jenkins (
Date: Thu Jan 28 1999 - 14:03:56 MET

Date: Thu, 28 Jan 1999 08:03:56 -0500
Message-Id: <>
From: "Adam P. Jenkins" <>
To: Michael Hicks <>
Subject: one-time initialization
In-Reply-To: <>

Michael Hicks writes:
> 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're reading the state from a file, then you could make global
not be a ref by writing

let global = readState "initFile"

You could even store the init filename in an environment variable so
that readState could read a different file on different program

As far as getting rid of the pattern matching, if the state can only
be one of several choices, then you could make several versions of f()
and g(), one for each pattern, and assign them from readState. That

let (global, f, g) = readState "initFile"

where readState returns different functions for f() and g() depending
on what state it reads.


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