1Memoize(3pm) Perl Programmers Reference Guide Memoize(3pm)
2
3
4
6 Memoize - Make functions faster by trading space for time
7
9 use Memoize;
10 memoize('slow_function');
11 slow_function(arguments); # Is faster than it was before
12
13 This is normally all you need to know. However, many options are
14 available:
15
16 memoize(function, options...);
17
18 Options include:
19
20 NORMALIZER => function
21 INSTALL => new_name
22
23 SCALAR_CACHE => 'MEMORY'
24 SCALAR_CACHE => ['HASH', \%cache_hash ]
25 SCALAR_CACHE => 'FAULT'
26 SCALAR_CACHE => 'MERGE'
27
28 LIST_CACHE => 'MEMORY'
29 LIST_CACHE => ['HASH', \%cache_hash ]
30 LIST_CACHE => 'FAULT'
31 LIST_CACHE => 'MERGE'
32
34 Memoizing a function makes it faster by trading space for time. It does
35 this by caching the return values of the function in a table. If you
36 call the function again with the same arguments, "memoize" jumps in and
37 gives you the value out of the table, instead of letting the function
38 compute the value all over again.
39
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 an array whose first element is one
295 of 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 Another reason to use "HASH" is to provide your own hash variable.
329 You can then inspect or modify the contents of the hash to gain
330 finer control over the cache management.
331
332 "TIE"
333 This option is no longer supported. It is still documented only to
334 aid in the debugging of old programs that use it. Old programs
335 should be converted to use the "HASH" option instead.
336
337 memoize ... ['TIE', PACKAGE, ARGS...]
338
339 is merely a shortcut for
340
341 require PACKAGE;
342 { tie my %cache, PACKAGE, ARGS...;
343 memoize ... [HASH => \%cache];
344 }
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 that the memoized function does not
356 distinguish between list and scalar context, and that return values
357 in both contexts should be stored together. Both "LIST_CACHE =>
358 MERGE" and "SCALAR_CACHE => MERGE" mean the same thing.
359
360 Consider this function:
361
362 sub complicated {
363 # ... time-consuming calculation of $result
364 return $result;
365 }
366
367 The "complicated" function will return the same numeric $result
368 regardless of whether it is called in list or in scalar context.
369
370 Normally, the following code will result in two calls to
371 "complicated", even if "complicated" is memoized:
372
373 $x = complicated(142);
374 ($y) = complicated(142);
375 $z = complicated(142);
376
377 The first call will cache the result, say 37, in the scalar cache;
378 the second will cache the list "(37)" in the list cache. The third
379 call doesn't call the real "complicated" function; it gets the
380 value 37 from the scalar cache.
381
382 Obviously, the second call to "complicated" is a waste of time, and
383 storing its return value is a waste of space. Specifying
384 "LIST_CACHE => MERGE" will make "memoize" use the same cache for
385 scalar and list context return values, so that the second call uses
386 the scalar cache that was populated by the first call.
387 "complicated" ends up being called only once, and both subsequent
388 calls return 37 from the cache, regardless of the calling context.
389
390 List values in scalar context
391
392 Consider this function:
393
394 sub iota { return reverse (1..$_[0]) }
395
396 This function normally returns a list. Suppose you memoize it and
397 merge the caches:
398
399 memoize 'iota', SCALAR_CACHE => 'MERGE';
400
401 @i7 = iota(7);
402 $i7 = iota(7);
403
404 Here the first call caches the list (1,2,3,4,5,6,7). The second call
405 does not really make sense. "Memoize" cannot guess what behavior "iota"
406 should have in scalar context without actually calling it in scalar
407 context. Normally "Memoize" would call "iota" in scalar context and
408 cache the result, but the "SCALAR_CACHE => 'MERGE'" option says not to
409 do that, but to use the cache list-context value instead. But it cannot
410 return a list of seven elements in a scalar context. In this case $i7
411 will receive the first element of the cached list value, namely 7.
412
413 Merged disk caches
414
415 Another use for "MERGE" is when you want both kinds of return values
416 stored in the same disk file; this saves you from having to deal with
417 two disk files instead of one. You can use a normalizer function to
418 keep the two sets of return values separate. For example:
419
420 local $MLDBM::UseDB = 'DB_File';
421 tie my %cache => 'MLDBM', $filename, ...;
422
423 memoize 'myfunc',
424 NORMALIZER => 'n',
425 SCALAR_CACHE => [HASH => \%cache],
426 LIST_CACHE => 'MERGE',
427 ;
428
429 sub n {
430 my $context = wantarray() ? 'L' : 'S';
431 # ... now compute the hash key from the arguments ...
432 $hashkey = "$context:$hashkey";
433 }
434
435 This normalizer function will store scalar context return values in the
436 disk file under keys that begin with "S:", and list context return
437 values under keys that begin with "L:".
438
440 "unmemoize"
441 There's an "unmemoize" function that you can import if you want to.
442 Why would you want to? Here's an example: Suppose you have your cache
443 tied to a DBM file, and you want to make sure that the cache is written
444 out to disk if someone interrupts the program. If the program exits
445 normally, this will happen anyway, but if someone types control-C or
446 something then the program will terminate immediately without
447 synchronizing the database. So what you can do instead is
448
449 $SIG{INT} = sub { unmemoize 'function' };
450
451 "unmemoize" accepts a reference to, or the name of a previously
452 memoized function, and undoes whatever it did to provide the memoized
453 version in the first place, including making the name refer to the
454 unmemoized version if appropriate. It returns a reference to the
455 unmemoized version of the function.
456
457 If you ask it to unmemoize a function that was never memoized, it
458 croaks.
459
460 "flush_cache"
461 flush_cache(function) will flush out the caches, discarding all the
462 cached data. The argument may be a function name or a reference to a
463 function. For finer control over when data is discarded or expired,
464 see the documentation for "Memoize::Expire", included in this package.
465
466 Note that if the cache is a tied hash, "flush_cache" will attempt to
467 invoke the "CLEAR" method on the hash. If there is no "CLEAR" method,
468 this will cause a run-time error.
469
470 An alternative approach to cache flushing is to use the "HASH" option
471 (see above) to request that "Memoize" use a particular hash variable as
472 its cache. Then you can examine or modify the hash at any time in any
473 way you desire. You may flush the cache by using "%hash = ()".
474
476 Memoization is not a cure-all:
477
478 • Do not memoize a function whose behavior depends on program state
479 other than its own arguments, such as global variables, the time of
480 day, or file input. These functions will not produce correct
481 results when memoized. For a particularly easy example:
482
483 sub f {
484 time;
485 }
486
487 This function takes no arguments, and as far as "Memoize" is
488 concerned, it always returns the same result. "Memoize" is wrong,
489 of course, and the memoized version of this function will call
490 "time" once to get the current time, and it will return that same
491 time every time you call it after that.
492
493 • Do not memoize a function with side effects.
494
495 sub f {
496 my ($a, $b) = @_;
497 my $s = $a + $b;
498 print "$a + $b = $s.\n";
499 }
500
501 This function accepts two arguments, adds them, and prints their
502 sum. Its return value is the number of characters it printed, but
503 you probably didn't care about that. But "Memoize" doesn't
504 understand that. If you memoize this function, you will get the
505 result you expect the first time you ask it to print the sum of 2
506 and 3, but subsequent calls will return 1 (the return value of
507 "print") without actually printing anything.
508
509 • Do not memoize a function that returns a data structure that is
510 modified by its caller.
511
512 Consider these functions: "getusers" returns a list of users
513 somehow, and then "main" throws away the first user on the list and
514 prints the rest:
515
516 sub main {
517 my $userlist = getusers();
518 shift @$userlist;
519 foreach $u (@$userlist) {
520 print "User $u\n";
521 }
522 }
523
524 sub getusers {
525 my @users;
526 # Do something to get a list of users;
527 \@users; # Return reference to list.
528 }
529
530 If you memoize "getusers" here, it will work right exactly once.
531 The reference to the users list will be stored in the memo table.
532 "main" will discard the first element from the referenced list.
533 The next time you invoke "main", "Memoize" will not call
534 "getusers"; it will just return the same reference to the same list
535 it got last time. But this time the list has already had its head
536 removed; "main" will erroneously remove another element from it.
537 The list will get shorter and shorter every time you call "main".
538
539 Similarly, this:
540
541 $u1 = getusers();
542 $u2 = getusers();
543 pop @$u1;
544
545 will modify $u2 as well as $u1, because both variables are
546 references to the same array. Had "getusers" not been memoized,
547 $u1 and $u2 would have referred to different arrays.
548
549 • Do not memoize a very simple function.
550
551 Recently someone mentioned to me that the Memoize module made his
552 program run slower instead of faster. It turned out that he was
553 memoizing the following function:
554
555 sub square {
556 $_[0] * $_[0];
557 }
558
559 I pointed out that "Memoize" uses a hash, and that looking up a
560 number in the hash is necessarily going to take a lot longer than a
561 single multiplication. There really is no way to speed up the
562 "square" function.
563
564 Memoization is not magical.
565
567 You can tie the cache tables to any sort of tied hash that you want to,
568 as long as it supports "TIEHASH", "FETCH", "STORE", and "EXISTS". For
569 example,
570
571 tie my %cache => 'GDBM_File', $filename, O_RDWR|O_CREAT, 0666;
572 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
573
574 works just fine. For some storage methods, you need a little glue.
575
576 "SDBM_File" doesn't supply an "EXISTS" method, so included in this
577 package is a glue module called "Memoize::SDBM_File" which does provide
578 one. Use this instead of plain "SDBM_File" to store your cache table
579 on disk in an "SDBM_File" database:
580
581 tie my %cache => 'Memoize::SDBM_File', $filename, O_RDWR|O_CREAT, 0666;
582 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
583
584 "NDBM_File" has the same problem and the same solution. (Use
585 "Memoize::NDBM_File instead of plain NDBM_File.")
586
587 "Storable" isn't a tied hash class at all. You can use it to store a
588 hash to disk and retrieve it again, but you can't modify the hash while
589 it's on the disk. So if you want to store your cache table in a
590 "Storable" database, use "Memoize::Storable", which puts a hashlike
591 front-end onto "Storable". The hash table is actually kept in memory,
592 and is loaded from your "Storable" file at the time you memoize the
593 function, and stored back at the time you unmemoize the function (or
594 when your program exits):
595
596 tie my %cache => 'Memoize::Storable', $filename;
597 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
598
599 tie my %cache => 'Memoize::Storable', $filename, 'nstore';
600 memoize 'function', SCALAR_CACHE => [HASH => \%cache];
601
602 Include the "nstore" option to have the "Storable" database written in
603 network order. (See Storable for more details about this.)
604
605 The flush_cache() function will raise a run-time error unless the tied
606 package provides a "CLEAR" method.
607
609 See Memoize::Expire, which is a plug-in module that adds expiration
610 functionality to Memoize. If you don't like the kinds of policies that
611 Memoize::Expire implements, it is easy to write your own plug-in module
612 to implement whatever policy you desire. Memoize comes with several
613 examples. An expiration manager that implements a LRU policy is
614 available on CPAN as Memoize::ExpireLRU.
615
617 The test suite is much better, but always needs improvement.
618
619 There is some problem with the way "goto &f" works under threaded Perl,
620 perhaps because of the lexical scoping of @_. This is a bug in Perl,
621 and until it is resolved, memoized functions will see a slightly
622 different caller() and will perform a little more slowly on threaded
623 perls than unthreaded perls.
624
625 Some versions of "DB_File" won't let you store data under a key of
626 length 0. That means that if you have a function "f" which you
627 memoized and the cache is in a "DB_File" database, then the value of
628 f() ("f" called with no arguments) will not be memoized. If this is a
629 big problem, you can supply a normalizer function that prepends "x" to
630 every key.
631
633 At <https://perl.plover.com/MiniMemoize/> there is an article about
634 memoization and about the internals of Memoize that appeared in The
635 Perl Journal, issue #13.
636
637 Mark-Jason Dominus's book Higher-Order Perl (2005, ISBN 1558607013,
638 published by Morgan Kaufmann) discusses memoization (and many other
639 topics) in tremendous detail. It is available on-line for free. For
640 more information, visit <https://hop.perl.plover.com/>.
641
643 Many thanks to Florian Ragwitz for administration and packaging
644 assistance, to John Tromp for bug reports, to Jonathan Roy for bug
645 reports and suggestions, to Michael Schwern for other bug reports and
646 patches, to Mike Cariaso for helping me to figure out the Right Thing
647 to Do About Expiration, to Joshua Gerth, Joshua Chamas, Jonathan Roy
648 (again), Mark D. Anderson, and Andrew Johnson for more suggestions
649 about expiration, to Brent Powers for the Memoize::ExpireLRU module, to
650 Ariel Scolnicov for delightful messages about the Fibonacci function,
651 to Dion Almaer for thought-provoking suggestions about the default
652 normalizer, to Walt Mankowski and Kurt Starsinic for much help
653 investigating problems under threaded Perl, to Alex Dudkevich for
654 reporting the bug in prototyped functions and for checking my patch, to
655 Tony Bass for many helpful suggestions, to Jonathan Roy (again) for
656 finding a use for unmemoize(), to Philippe Verdret for enlightening
657 discussion of "Hook::PrePostCall", to Nat Torkington for advice I
658 ignored, to Chris Nandor for portability advice, to Randal Schwartz for
659 suggesting the '"flush_cache" function, and to Jenda Krynicky for being
660 a light in the world.
661
662 Special thanks to Jarkko Hietaniemi, the 5.8.0 pumpking, for including
663 this module in the core and for his patient and helpful guidance during
664 the integration process.
665
667 Mark Jason Dominus
668
670 This software is copyright (c) 2012 by Mark Jason Dominus.
671
672 This is free software; you can redistribute it and/or modify it under
673 the same terms as the Perl 5 programming language system itself.
674
675
676
677perl v5.38.2 2023-11-30 Memoize(3pm)