| Next | The Perl Hardware Store | DC.pm Version | 29 |
Caching is a common strategy for speeding up a pure function
The first time you call it, it remembers its return value
If you call it again with the same arguments, it returns the cached value
{ my @fact = ();
sub factorial {
my $n = shift;
return $fact[$n]
if defined $fact[$n];
$fact[$n] =
($n == 0 ? 1
: $n * factorial($n-1));
}
}
There aren't that many simple good ideas
Caching is one
As a result, it is used everywhere
| Next | ![]() |
Copyright © 2003 M. J. Dominus |