TheoPetersen has asked for the wisdom of the Perl Monks concerning the following question:
My code checks a definition to see if it has one of these snippets, and replaces the snippet with a code reference to a compiled function the first time it is used. A given application definition might contain a large number of these small functions, and chances are good there will be duplicates, so I wanted to gain further efficiency by caching the compiled versions and sharing the cache among all the object definitions.
The first thing that came to mind was to construct a hash keyed on an MD5 hash of the function. But as I was starting to put that together, I wondered if a plain hash wouldn't be just as simple and easy. That is, given a bit of Perl in $code, store it like:
Given that Perl is going use its own hash function on the text of the code to construct the internal key value, this seemed equivalent to the MD5 version and probably faster. I would have stored the text of the code somewhere anyway for debugging purposes; the fact that a regular hash does this for me is just gravy.$function_cache{$code} = eval "sub {$code}"; if ($@) { # handle bad code errors... }
Am I doing anything terrible to Perl in using a hash with longer than usual keys? Any suggestions on better approaches?
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(tye)Re: Cache of small functions
by tye (Sage) on Mar 21, 2001 at 23:32 UTC | |
by merlyn (Sage) on Mar 21, 2001 at 23:49 UTC |