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