Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Re: use Memoize;

by sundialsvc4 (Abbot)
on Jul 17, 2018 at 20:12 UTC ( #1218694=note: print w/replies, xml ) Need Help??

in reply to use Memoize;

This might not work as you intended.   Memoize is fine if your function does not do anything, but is simply a mathematical function that is intended only to return a result.   And, it is “voodoo” in the sense that every “function call” might or might not actually happen, and the logic which makes this determination is nowhere to be seen.   This can waste an awful lot of time and head-banging.   It is a clever trick only if you know the trick, and only if you know to expect it.

A better strategy IMHO would be to arrange for the function to cache its “expensive data structure” but to do so explicitly.   The structure is referenced in a global and is initialized (and stashed in the global) only when that global is undef.   (You can also use “freeze and thaw” techniques.)   Now, the function will be both efficient and(!) clear as to what it is doing, because it is doing it.   When a call is made, a call always takes place, and the now-efficient logic is executed as part of that.

It is really not at all difficult to explicitly do within any function the sort of thing that Memoize does, and what it does not:

if key 'k' is not in the stash { stash[k] = expensive_computation } do anything else that needs to be done when this function is called(!) return stash[k];
... but now you can see it. Your opinions may vary.

Replies are listed 'Best First'.
Re^2: use Memoize;
by Corion (Pope) on Jul 17, 2018 at 20:16 UTC

    Alternatively, instead of writing your own caching scheme, you could use a proven and documented approach, and use Memoize.

    Also, the technical term for what you describe as "simply a mathematical function that is intended to return a result" is "pure function" or a subroutine without side-effects. Because, as the documentation of Memoize says, it will cache the results of a function for identical input values.

      A reply falls below the community's threshold of quality. You may see it by logging in.

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://1218694]
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (7)
As of 2019-12-12 18:25 GMT
Find Nodes?
    Voting Booth?

    No recent polls found