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