1Memoize(3pm) Perl Programmers Reference Guide Memoize(3pm)
2
3
4
6 Memoize - Make functions faster by trading space for time
7
9 # This is the documentation for Memoize 1.01
10 use Memoize;
11 memoize('slow_function');
12 slow_function(arguments); # Is faster than it was before
13
14 This is normally all you need to know. However, many options are
15 available:
16
17 memoize(function, options...);
18
19 Options include:
20
21 NORMALIZER => function
22 INSTALL => new_name
23
24 SCALAR_CACHE => 'MEMORY'
25 SCALAR_CACHE => ['HASH', \%cache_hash ]
26 SCALAR_CACHE => 'FAULT'
27 SCALAR_CACHE => 'MERGE'
28
29 LIST_CACHE => 'MEMORY'
30 LIST_CACHE => ['HASH', \%cache_hash ]
31 LIST_CACHE => 'FAULT'
32 LIST_CACHE => 'MERGE'
33
35 `Memoizing' a function makes it faster by trading space for time. It
36 does this by caching the return values of the function in a table. If
37 you call the function again with the same arguments, "memoize" jumps in
38 and gives you the value out of the table, instead of letting the func‐
39 tion compute the value all over again.
40
41 Here is an extreme example. Consider the Fibonacci sequence, defined
42 by the following function:
43
44 # Compute Fibonacci numbers
45 sub fib {
46 my $n = shift;
47 return $n if $n < 2;
48 fib($n-1) + fib($n-2);
49 }
50
51 This function is very slow. Why? To compute fib(14), it first wants
52 to compute fib(13) and fib(12), and add the results. But to compute
53 fib(13), it first has to compute fib(12) and fib(11), and then it comes
54 back and computes fib(12) all over again even though the answer is the
55 same. And both of the times that it wants to compute fib(12), it has
56 to compute fib(11) from scratch, and then it has to do it again each
57 time it wants to compute fib(13). This function does so much recomput‐
58 ing of old results that it takes a really long time to run---fib(14)
59 makes 1,200 extra recursive calls to itself, to compute and recompute
60 things that it already computed.
61
62 This function is a good candidate for memoization. If you memoize the
63 `fib' function above, it will compute fib(14) exactly once, the first
64 time it needs to, and then save the result in a table. Then if you ask
65 for fib(14) again, it gives you the result out of the table. While
66 computing fib(14), instead of computing fib(12) twice, it does it once;
67 the second time it needs the value it gets it from the table. It
68 doesn't compute fib(11) four times; it computes it once, getting it
69 from the table the next three times. Instead of making 1,200 recursive
70 calls to `fib', it makes 15. This makes the function about 150 times
71 faster.
72
73 You could do the memoization yourself, by rewriting the function, like
74 this:
75
76 # Compute Fibonacci numbers, memoized version
77 { my @fib;
78 sub fib {
79 my $n = shift;
80 return $fib[$n] if defined $fib[$n];
81 return $fib[$n] = $n if $n < 2;
82 $fib[$n] = fib($n-1) + fib($n-2);
83 }
84 }
85
86 Or you could use this module, like this:
87
88 use Memoize;
89 memoize('fib');
90
91 # Rest of the fib function just like the original version.
92
93 This makes it easy to turn memoizing on and off.
94
95 Here's an even simpler example: I wrote a simple ray tracer; the pro‐
96 gram would look in a certain direction, figure out what it was looking
97 at, and then convert the `color' value (typically a string like `red')
98 of that object to a red, green, and blue pixel value, like this:
99
100 for ($direction = 0; $direction < 300; $direction++) {
101 # Figure out which object is in direction $direction
102 $color = $object->{color};
103 ($r, $g, $b) = @{&ColorToRGB($color)};
104 ...
105 }
106
107 Since there are relatively few objects in a picture, there are only a
108 few colors, which get looked up over and over again. Memoizing "Color‐
109 ToRGB" sped up the program by several percent.
110
112 This module exports exactly one function, "memoize". The rest of the
113 functions in this package are None of Your Business.
114
115 You should say
116
117 memoize(function)
118
119 where "function" is the name of the function you want to memoize, or a
120 reference to it. "memoize" returns a reference to the new, memoized
121 version of the function, or "undef" on a non-fatal error. At present,
122 there are no non-fatal errors, but there might be some in the future.
123
124 If "function" was the name of a function, then "memoize" hides the old
125 version and installs the new memoized version under the old name, so
126 that "&function(...)" actually invokes the memoized version.
127
129 There are some optional options you can pass to "memoize" to change the
130 way it behaves a little. To supply options, invoke "memoize" like
131 this:
132
133 memoize(function, NORMALIZER => function,
134 INSTALL => newname,
135 SCALAR_CACHE => option,
136 LIST_CACHE => option
137 );
138
139 Each of these options is optional; you can include some, all, or none
140 of them.
141
142 INSTALL
143
144 If you supply a function name with "INSTALL", memoize will install the
145 new, memoized version of the function under the name you give. For
146 example,
147
148 memoize('fib', INSTALL => 'fastfib')
149
150 installs the memoized version of "fib" as "fastfib"; without the
151 "INSTALL" option it would have replaced the old "fib" with the memoized
152 version.
153
154 To prevent "memoize" from installing the memoized version anywhere, use
155 "INSTALL => undef".
156
157 NORMALIZER
158
159 Suppose your function looks like this:
160
161 # Typical call: f('aha!', A => 11, B => 12);
162 sub f {
163 my $a = shift;
164 my %hash = @_;
165 $hash{B} ⎪⎪= 2; # B defaults to 2
166 $hash{C} ⎪⎪= 7; # C defaults to 7
167
168 # Do something with $a, %hash
169 }
170
171 Now, the following calls to your function are all completely equiva‐
172 lent:
173
174 f(OUCH);
175 f(OUCH, B => 2);
176 f(OUCH, C => 7);
177 f(OUCH, B => 2, C => 7);
178 f(OUCH, C => 7, B => 2);
179 (etc.)
180
181 However, unless you tell "Memoize" that these calls are equivalent, it
182 will not know that, and it will compute the values for these invoca‐
183 tions of your function separately, and store them separately.
184
185 To prevent this, supply a "NORMALIZER" function that turns the program
186 arguments into a string in a way that equivalent arguments turn into
187 the same string. A "NORMALIZER" function for "f" above might look like
188 this:
189
190 sub normalize_f {
191 my $a = shift;
192 my %hash = @_;
193 $hash{B} ⎪⎪= 2;
194 $hash{C} ⎪⎪= 7;
195
196 join(',', $a, map ($_ => $hash{$_}) sort keys %hash);
197 }
198
199 Each of the argument lists above comes out of the "normalize_f" func‐
200 tion looking exactly the same, like this:
201
202 OUCH,B,2,C,7
203
204 You would tell "Memoize" to use this normalizer this way:
205
206 memoize('f', NORMALIZER => 'normalize_f');
207
208 "memoize" knows that if the normalized version of the arguments is the
209 same for two argument lists, then it can safely look up the value that
210 it computed for one argument list and return it as the result of call‐
211 ing the function with the other argument list, even if the argument
212 lists look different.
213
214 The default normalizer just concatenates the arguments with character
215 28 in between. (In ASCII, this is called FS or control-\.) This
216 always works correctly for functions with only one string argument, and
217 also when the arguments never contain character 28. However, it can
218 confuse certain argument lists:
219
220 normalizer("a\034", "b")
221 normalizer("a", "\034b")
222 normalizer("a\034\034b")
223
224 for example.
225
226 Since hash keys are strings, the default normalizer will not distin‐
227 guish between "undef" and the empty string. It also won't work when
228 the function's arguments are references. For example, consider a func‐
229 tion "g" which gets two arguments: A number, and a reference to an
230 array of numbers:
231
232 g(13, [1,2,3,4,5,6,7]);
233
234 The default normalizer will turn this into something like
235 "13\034ARRAY(0x436c1f)". That would be all right, except that a subse‐
236 quent array of numbers might be stored at a different location even
237 though it contains the same data. If this happens, "Memoize" will
238 think that the arguments are different, even though they are equiva‐
239 lent. In this case, a normalizer like this is appropriate:
240
241 sub normalize { join ' ', $_[0], @{$_[1]} }
242
243 For the example above, this produces the key "13 1 2 3 4 5 6 7".
244
245 Another use for normalizers is when the function depends on data other
246 than those in its arguments. Suppose you have a function which returns
247 a value which depends on the current hour of the day:
248
249 sub on_duty {
250 my ($problem_type) = @_;
251 my $hour = (localtime)[2];
252 open my $fh, "$DIR/$problem_type" or die...;
253 my $line;
254 while ($hour-- > 0)
255 $line = <$fh>;
256 }
257 return $line;
258 }
259
260 At 10:23, this function generates the 10th line of a data file; at 3:45
261 PM it generates the 15th line instead. By default, "Memoize" will only
262 see the $problem_type argument. To fix this, include the current hour
263 in the normalizer:
264
265 sub normalize { join ' ', (localtime)[2], @_ }
266
267 The calling context of the function (scalar or list context) is propa‐
268 gated to the normalizer. This means that if the memoized function will
269 treat its arguments differently in list context than it would in scalar
270 context, you can have the normalizer function select its behavior based
271 on the results of "wantarray". Even if called in a list context, a
272 normalizer should still return a single string.
273
274 "SCALAR_CACHE", "LIST_CACHE"
275
276 Normally, "Memoize" caches your function's return values into an ordi‐
277 nary Perl hash variable. However, you might like to have the values
278 cached on the disk, so that they persist from one run of your program
279 to the next, or you might like to associate some other interesting
280 semantics with the cached values.
281
282 There's a slight complication under the hood of "Memoize": There are
283 actually two caches, one for scalar values and one for list values.
284 When your function is called in scalar context, its return value is
285 cached in one hash, and when your function is called in list context,
286 its value is cached in the other hash. You can control the caching
287 behavior of both contexts independently with these options.
288
289 The argument to "LIST_CACHE" or "SCALAR_CACHE" must either be one of
290 the following four strings:
291
292 MEMORY
293 FAULT
294 MERGE
295 HASH
296
297 or else it must be a reference to a list whose first element is one of
298 these four strings, such as "[HASH, arguments...]".
299
300 "MEMORY"
301 "MEMORY" means that return values from the function will be cached
302 in an ordinary Perl hash variable. The hash variable will not per‐
303 sist after the program exits. This is the default.
304
305 "HASH"
306 "HASH" allows you to specify that a particular hash that you supply
307 will be used as the cache. You can tie this hash beforehand to
308 give it any behavior you want.
309
310 A tied hash can have any semantics at all. It is typically tied to
311 an on-disk database, so that cached values are stored in the data‐
312 base and retrieved from it again when needed, and the disk file
313 typically persists after your program has exited. See "perltie"
314 for more complete details about "tie".
315
316 A typical example is:
317
318 use DB_File;
319 tie my %cache => 'DB_File', $filename, O_RDWR⎪O_CREAT, 0666;
320 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
321
322 This has the effect of storing the cache in a "DB_File" database
323 whose name is in $filename. The cache will persist after the pro‐
324 gram has exited. Next time the program runs, it will find the
325 cache already populated from the previous run of the program. Or
326 you can forcibly populate the cache by constructing a batch program
327 that runs in the background and populates the cache file. Then
328 when you come to run your real program the memoized function will
329 be fast because all its results have been precomputed.
330
331 "TIE"
332 This option is no longer supported. It is still documented only to
333 aid in the debugging of old programs that use it. Old programs
334 should be converted to use the "HASH" option instead.
335
336 memoize ... [TIE, PACKAGE, ARGS...]
337
338 is merely a shortcut for
339
340 require PACKAGE;
341 { my %cache;
342 tie %cache, PACKAGE, ARGS...;
343 }
344 memoize ... [HASH => \%cache];
345
346 "FAULT"
347 "FAULT" means that you never expect to call the function in scalar
348 (or list) context, and that if "Memoize" detects such a call, it
349 should abort the program. The error message is one of
350
351 `foo' function called in forbidden list context at line ...
352 `foo' function called in forbidden scalar context at line ...
353
354 "MERGE"
355 "MERGE" normally means the function does not distinguish between
356 list and sclar context, and that return values in both contexts
357 should be stored together. "LIST_CACHE => MERGE" means that list
358 context return values should be stored in the same hash that is
359 used for scalar context returns, and "SCALAR_CACHE => MERGE" means
360 the same, mutatis mutandis. It is an error to specify "MERGE" for
361 both, but it probably does something useful.
362
363 Consider this function:
364
365 sub pi { 3; }
366
367 Normally, the following code will result in two calls to "pi":
368
369 $x = pi();
370 ($y) = pi();
371 $z = pi();
372
373 The first call caches the value 3 in the scalar cache; the second
374 caches the list "(3)" in the list cache. The third call doesn't
375 call the real "pi" function; it gets the value from the scalar
376 cache.
377
378 Obviously, the second call to "pi" is a waste of time, and storing
379 its return value is a waste of space. Specifying "LIST_CACHE =>
380 MERGE" will make "memoize" use the same cache for scalar and list
381 context return values, so that the second call uses the scalar
382 cache that was populated by the first call. "pi" ends up being
383 called only once, and both subsequent calls return 3 from the
384 cache, regardless of the calling context.
385
386 Another use for "MERGE" is when you want both kinds of return val‐
387 ues stored in the same disk file; this saves you from having to
388 deal with two disk files instead of one. You can use a normalizer
389 function to keep the two sets of return values separate. For exam‐
390 ple:
391
392 tie my %cache => 'MLDBM', 'DB_File', $filename, ...;
393
394 memoize 'myfunc',
395 NORMALIZER => 'n',
396 SCALAR_CACHE => [HASH => \%cache],
397 LIST_CACHE => MERGE,
398 ;
399
400 sub n {
401 my $context = wantarray() ? 'L' : 'S';
402 # ... now compute the hash key from the arguments ...
403 $hashkey = "$context:$hashkey";
404 }
405
406 This normalizer function will store scalar context return values in
407 the disk file under keys that begin with "S:", and list context
408 return values under keys that begin with "L:".
409
411 "unmemoize"
412
413 There's an "unmemoize" function that you can import if you want to.
414 Why would you want to? Here's an example: Suppose you have your cache
415 tied to a DBM file, and you want to make sure that the cache is written
416 out to disk if someone interrupts the program. If the program exits
417 normally, this will happen anyway, but if someone types control-C or
418 something then the program will terminate immediately without synchro‐
419 nizing the database. So what you can do instead is
420
421 $SIG{INT} = sub { unmemoize 'function' };
422
423 "unmemoize" accepts a reference to, or the name of a previously memo‐
424 ized function, and undoes whatever it did to provide the memoized ver‐
425 sion in the first place, including making the name refer to the unmemo‐
426 ized version if appropriate. It returns a reference to the unmemoized
427 version of the function.
428
429 If you ask it to unmemoize a function that was never memoized, it
430 croaks.
431
432 "flush_cache"
433
434 "flush_cache(function)" will flush out the caches, discarding all the
435 cached data. The argument may be a function name or a reference to a
436 function. For finer control over when data is discarded or expired,
437 see the documentation for "Memoize::Expire", included in this package.
438
439 Note that if the cache is a tied hash, "flush_cache" will attempt to
440 invoke the "CLEAR" method on the hash. If there is no "CLEAR" method,
441 this will cause a run-time error.
442
443 An alternative approach to cache flushing is to use the "HASH" option
444 (see above) to request that "Memoize" use a particular hash variable as
445 its cache. Then you can examine or modify the hash at any time in any
446 way you desire. You may flush the cache by using "%hash = ()".
447
449 Memoization is not a cure-all:
450
451 · Do not memoize a function whose behavior depends on program state
452 other than its own arguments, such as global variables, the time of
453 day, or file input. These functions will not produce correct
454 results when memoized. For a particularly easy example:
455
456 sub f {
457 time;
458 }
459
460 This function takes no arguments, and as far as "Memoize" is con‐
461 cerned, it always returns the same result. "Memoize" is wrong, of
462 course, and the memoized version of this function will call "time"
463 once to get the current time, and it will return that same time
464 every time you call it after that.
465
466 · Do not memoize a function with side effects.
467
468 sub f {
469 my ($a, $b) = @_;
470 my $s = $a + $b;
471 print "$a + $b = $s.\n";
472 }
473
474 This function accepts two arguments, adds them, and prints their
475 sum. Its return value is the numuber of characters it printed, but
476 you probably didn't care about that. But "Memoize" doesn't under‐
477 stand that. If you memoize this function, you will get the result
478 you expect the first time you ask it to print the sum of 2 and 3,
479 but subsequent calls will return 1 (the return value of "print")
480 without actually printing anything.
481
482 · Do not memoize a function that returns a data structure that is
483 modified by its caller.
484
485 Consider these functions: "getusers" returns a list of users some‐
486 how, and then "main" throws away the first user on the list and
487 prints the rest:
488
489 sub main {
490 my $userlist = getusers();
491 shift @$userlist;
492 foreach $u (@$userlist) {
493 print "User $u\n";
494 }
495 }
496
497 sub getusers {
498 my @users;
499 # Do something to get a list of users;
500 \@users; # Return reference to list.
501 }
502
503 If you memoize "getusers" here, it will work right exactly once.
504 The reference to the users list will be stored in the memo table.
505 "main" will discard the first element from the referenced list.
506 The next time you invoke "main", "Memoize" will not call
507 "getusers"; it will just return the same reference to the same list
508 it got last time. But this time the list has already had its head
509 removed; "main" will erroneously remove another element from it.
510 The list will get shorter and shorter every time you call "main".
511
512 Similarly, this:
513
514 $u1 = getusers();
515 $u2 = getusers();
516 pop @$u1;
517
518 will modify $u2 as well as $u1, because both variables are refer‐
519 ences to the same array. Had "getusers" not been memoized, $u1 and
520 $u2 would have referred to different arrays.
521
522 · Do not memoize a very simple function.
523
524 Recently someone mentioned to me that the Memoize module made his
525 program run slower instead of faster. It turned out that he was
526 memoizing the following function:
527
528 sub square {
529 $_[0] * $_[0];
530 }
531
532 I pointed out that "Memoize" uses a hash, and that looking up a
533 number in the hash is necessarily going to take a lot longer than a
534 single multiplication. There really is no way to speed up the
535 "square" function.
536
537 Memoization is not magical.
538
540 You can tie the cache tables to any sort of tied hash that you want to,
541 as long as it supports "TIEHASH", "FETCH", "STORE", and "EXISTS". For
542 example,
543
544 tie my %cache => 'GDBM_File', $filename, O_RDWR⎪O_CREAT, 0666;
545 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
546
547 works just fine. For some storage methods, you need a little glue.
548
549 "SDBM_File" doesn't supply an "EXISTS" method, so included in this
550 package is a glue module called "Memoize::SDBM_File" which does provide
551 one. Use this instead of plain "SDBM_File" to store your cache table
552 on disk in an "SDBM_File" database:
553
554 tie my %cache => 'Memoize::SDBM_File', $filename, O_RDWR⎪O_CREAT, 0666;
555 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
556
557 "NDBM_File" has the same problem and the same solution. (Use "Memo‐
558 ize::NDBM_File instead of plain NDBM_File.")
559
560 "Storable" isn't a tied hash class at all. You can use it to store a
561 hash to disk and retrieve it again, but you can't modify the hash while
562 it's on the disk. So if you want to store your cache table in a
563 "Storable" database, use "Memoize::Storable", which puts a hashlike
564 front-end onto "Storable". The hash table is actually kept in memory,
565 and is loaded from your "Storable" file at the time you memoize the
566 function, and stored back at the time you unmemoize the function (or
567 when your program exits):
568
569 tie my %cache => 'Memoize::Storable', $filename;
570 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
571
572 tie my %cache => 'Memoize::Storable', $filename, 'nstore';
573 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
574
575 Include the `nstore' option to have the "Storable" database written in
576 `network order'. (See Storable for more details about this.)
577
578 The "flush_cache()" function will raise a run-time error unless the
579 tied package provides a "CLEAR" method.
580
582 See Memoize::Expire, which is a plug-in module that adds expiration
583 functionality to Memoize. If you don't like the kinds of policies that
584 Memoize::Expire implements, it is easy to write your own plug-in module
585 to implement whatever policy you desire. Memoize comes with several
586 examples. An expiration manager that implements a LRU policy is avail‐
587 able on CPAN as Memoize::ExpireLRU.
588
590 The test suite is much better, but always needs improvement.
591
592 There is some problem with the way "goto &f" works under threaded Perl,
593 perhaps because of the lexical scoping of @_. This is a bug in Perl,
594 and until it is resolved, memoized functions will see a slightly dif‐
595 ferent "caller()" and will perform a little more slowly on threaded
596 perls than unthreaded perls.
597
598 Some versions of "DB_File" won't let you store data under a key of
599 length 0. That means that if you have a function "f" which you memo‐
600 ized and the cache is in a "DB_File" database, then the value of "f()"
601 ("f" called with no arguments) will not be memoized. If this is a big
602 problem, you can supply a normalizer function that prepends "x" to
603 every key.
604
606 To join a very low-traffic mailing list for announcements about "Memo‐
607 ize", send an empty note to "mjd-perl-memoize-request@plover.com".
608
610 Mark-Jason Dominus ("mjd-perl-memoize+@plover.com"), Plover Systems co.
611
612 See the "Memoize.pm" Page at http://www.plover.com/~mjd/perl/Memoize/
613 for news and upgrades. Near this page, at
614 http://www.plover.com/~mjd/perl/MiniMemoize/ there is an article about
615 memoization and about the internals of Memoize that appeared in The
616 Perl Journal, issue #13. (This article is also included in the Memoize
617 distribution as `article.html'.)
618
619 My upcoming book will discuss memoization (and many other fascinating
620 topics) in tremendous detail. It will be published by Morgan Kaufmann
621 in 2002, possibly under the title Perl Advanced Techniques Handbook.
622 It will also be available on-line for free. For more information,
623 visit http://perl.plover.com/book/ .
624
625 To join a mailing list for announcements about "Memoize", send an empty
626 message to "mjd-perl-memoize-request@plover.com". This mailing list is
627 for announcements only and has extremely low traffic---about two mes‐
628 sages per year.
629
631 Copyright 1998, 1999, 2000, 2001 by Mark Jason Dominus
632
633 This library is free software; you may redistribute it and/or modify it
634 under the same terms as Perl itself.
635
637 Many thanks to Jonathan Roy for bug reports and suggestions, to Michael
638 Schwern for other bug reports and patches, to Mike Cariaso for helping
639 me to figure out the Right Thing to Do About Expiration, to Joshua
640 Gerth, Joshua Chamas, Jonathan Roy (again), Mark D. Anderson, and
641 Andrew Johnson for more suggestions about expiration, to Brent Powers
642 for the Memoize::ExpireLRU module, to Ariel Scolnicov for delightful
643 messages about the Fibonacci function, to Dion Almaer for thought-pro‐
644 voking suggestions about the default normalizer, to Walt Mankowski and
645 Kurt Starsinic for much help investigating problems under threaded
646 Perl, to Alex Dudkevich for reporting the bug in prototyped functions
647 and for checking my patch, to Tony Bass for many helpful suggestions,
648 to Jonathan Roy (again) for finding a use for "unmemoize()", to
649 Philippe Verdret for enlightening discussion of "Hook::PrePostCall", to
650 Nat Torkington for advice I ignored, to Chris Nandor for portability
651 advice, to Randal Schwartz for suggesting the '"flush_cache" function,
652 and to Jenda Krynicky for being a light in the world.
653
654 Special thanks to Jarkko Hietaniemi, the 5.8.0 pumpking, for including
655 this module in the core and for his patient and helpful guidance during
656 the integration process.
657
658
659
660perl v5.8.8 2001-09-21 Memoize(3pm)