Beefy Boxes and Bandwidth Generously Provided by pair Networks Frank
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Cache of small functions

by TheoPetersen (Priest)
on Mar 21, 2001 at 18:15 UTC ( [id://66105]=perlquestion: print w/replies, xml ) Need Help??

This is an archived low-energy page for bots and other anonmyous visitors. Please sign up if you are a human and want to interact.

TheoPetersen has asked for the wisdom of the Perl Monks concerning the following question:

One of my projects allows customization via small (presumably) bits of Perl code embedded in a definition (something that isn't XML but soon will be). These are functions for (say) formatting a data element or calculating a field when a record is retrieved. They are written by responsible parties (either my co-workers or knowledgable folks at customer sites) so I don't need to worry about the actions taken by the code.

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:

$function_cache{$code} = eval "sub {$code}"; if ($@) { # handle bad code errors... }
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.

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 18:32 UTC

    A buffer will be allocated and the source for the subroutine copied into it. For short routines that is no big deal, especially if you aren't also caching the source code some other place.

            - tye (but my friends call me "Tye")

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: perlquestion [id://66105]
Approved by root
help
Sections?
Information?
Find Nodes?
Leftovers?
    Notices?
    hippoepoptai's answer Re: how do I set a cookie and redirect was blessed by hippo!
    erzuuliAnonymous Monks are no longer allowed to use Super Search, due to an excessive use of this resource by robots.