From mboxrd@z Thu Jan 1 00:00:00 1970 Received: (from weis@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id NAA21669 for caml-redistribution; Thu, 28 Jan 1999 13:23:04 +0100 (MET) Received: from concorde.inria.fr (concorde.inria.fr [192.93.2.39]) by pauillac.inria.fr (8.7.6/8.7.3) with ESMTP id LAA23252 for ; Thu, 28 Jan 1999 11:38:34 +0100 (MET) Received: from pauillac.inria.fr (pauillac.inria.fr [128.93.11.35]) by concorde.inria.fr (8.8.7/8.8.7) with ESMTP id LAA16136; Thu, 28 Jan 1999 11:38:29 +0100 (MET) Received: (from xleroy@localhost) by pauillac.inria.fr (8.7.6/8.7.3) id LAA07594; Thu, 28 Jan 1999 11:38:29 +0100 (MET) Message-ID: <19990128113829.62982@pauillac.inria.fr> Date: Thu, 28 Jan 1999 11:38:29 +0100 From: Xavier Leroy To: Michael Hicks , caml-list@inria.fr Subject: Re: one-time initialization References: <199901280508.AAA21644@codex.cis.upenn.edu> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Mailer: Mutt 0.89.1 In-Reply-To: <199901280508.AAA21644@codex.cis.upenn.edu>; from Michael Hicks on Thu, Jan 28, 1999 at 12:08:23AM -0500 Sender: weis > 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; The compiler certainly cannot do it for you, as it involves proving that f and g are never applied before init is called... > 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. Here are a couple of faster, but perhaps less modular approaches: * Get rid of the ref and the option, and initialize "global" with the right value the first time. That involves reading the file when global is initialized, which might involve parsing (partially) the command-line to find the right file name. E.g.: let global = let filename = in read_config_file global let f() = ... use global ... * Keep the ref but get rid of the option. You then need a dummy value of the type of your global state, and you're also no longer protected against forgetting to initialize it. let global = ref dummy_global_value let init i = global := i let f() = ... use !global ... Regards, - Xavier Leroy