![]() |
|
Think about Loose Coupling | |
PerlMonks |
Reminder to self: must use Memoize more often!by tobyink (Canon) |
on Jan 12, 2013 at 12:13 UTC ( #1013033=CUFP: print w/replies, xml ) | Need Help?? |
For functions which are non-volatile (i.e. the same inputs will always produce the same outputs) with no side-effects, it often makes sense to "memoize" them. That is, cache the results for the next time they're called. This is an especially good idea in the case of recursive functions. The following benchmark script illustrates the massive speed up.
The Memoize module gives you a pretty decent speed up, without needing to change the guts of the function. Just add memoize('fib2') and the Memoize module will wrap the original function with memoization code. The manually memoized version is clearly faster still, because it avoids the overhead of function wrapping - the memoization code is added to the guts of the function. Of course, there's no such thing as a free lunch - you're trading CPU for memory.
perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'
Back to
Cool Uses for Perl
|
|