CHI::Memoize(3pm)
π CHI::Memoize π
okay bestie, gather round, because this is the manual page for CHI::Memoize β a Perl module from the User Contributed Perl Documentation section (yes it's 3pm, we stan a perl module). It's called CHI::Memoize, and it is literally about to make your slow little functions go zoom. π¦
β¨ VERSION β¨
this is version 0.07 β that's the version, no cap.
πΈ SYNOPSIS πΈ
okay so here's the whole vibe in code form, look at it:
use CHI::Memoize qw(:all);
# Straight memoization in memory
memoize('func');
memoize('Some::Package::func');
# Memoize to a file or to memcached
memoize( 'func', driver => 'File', root_dir => '/path/to/cache' );
memoize( 'func', driver => 'Memcached', servers => ["127.0.0.1:11211"] );
# Expire after one hour
memoize('func', expires_in => '1h');
# Memoize based on the second and third argument to func
memoize('func', key => sub { $_[1], $_[2] });
like. that's it. that's the whole energy. π
π DESCRIPTION π
so the original Memoize docs said it best, and I'm quoting them here:
"`Memoizing' a function makes it faster by trading space for time. It does this by caching the return values of the function in a table. If you call the function again with the same arguments, "memoize" jumps in and gives you the value out of the table, instead of letting the function compute the value all over again."
β quoted from the original Memoize
if you want the lore and the motivation behind this whole thing, go read:
http://www.openswartz.com/2012/05/06/memoize-revisiting-a-twelve-year-old-api/
CHI::Memoize gives you the exact same facility as Memoize, but it's backed by CHI. which means, among other things, that you can:
- specify expiration times (
expires_in) and conditions (expire_if) β° - memoize to different backends, e.g.
File,Memcached,DBI, or to multilevel caches ποΈ - handle arbitrarily complex function arguments (via CHI key serialization) π§
π« FUNCTIONS π«
all of these are importable; only memoize is imported by default. use Memoize qw(:all) will import them all plus the NO_MEMOIZE constant. (yes, that's use Memoize, that's what the page says, don't come for me.)
memoize ($func, %options)
creates a new function wrapped around $func that caches results based on the passed arguments. periodt.
$func can be a function name (with or without a package prefix) or an anonymous function. if it's a name, that name gets rebound to the new function. either way, you get a code ref to the new wrapper function back. π
# Memoize a named function
memoize('func');
memoize('Some::Package::func');
# Memoize an anonymous function
$anon = memoize($anon);
by default, the cache key is formed from combining the full function name, the calling context (L or S), and all the function arguments with canonical JSON (sorted hash keys). so like, these calls get memoized together:
memoized_function({a => 5, b => 6, c => { d => 7, e => 8 }});
memoized_function({b => 6, c => { e => 8, d => 7 }, a => 5});
because those two hashes are canonically the same. iconic behavior honestly. but these get memoized separately because of context:
my $scalar = memoized_function(5);
my @list = memoized_function(5);
by default, the cache namespace is formed from the full function name or the stringified code reference. this lets you introspect and clear the memoized results for a particular function. π§
memoize throws an error if $func is already memoized. (rude, but fair.)
see OPTIONS below for what can go in the options hash. π
memoized ($func)
returns a CHI::Memoize::Info object if $func has been memoized, or undef if it hasn't.
# The CHI cache where memoize results are stored
#
my $cache = memoized($func)->cache;
$cache->clear;
# Code references to the original function and to the new wrapped function
#
my $orig = memoized($func)->orig;
my $wrapped = memoized($func)->wrapped;
unmemoize ($func)
removes the wrapper around $func, restoring it to its original unmemoized state. also clears the memoize cache if possible (not supported by all drivers, particularly memcached β sad, I know). throws an error if $func has not been memoized. π
memoize('Some::Package::func');
...
unmemoize('Some::Package::func');
β OPTIONS β
the following options can be passed to memoize.
keyβ specifies a code reference that takes arguments passed to the function and returns a cache key. the key may be returned as a list, list reference or hash reference; it will automatically be serialized to JSON in canonical mode (sorted hash keys). for example, this uses the second and third argument to the function as a key:
memoize('func', key => sub { @_[1..2] });
and this one is useful for functions that accept a list of key/value pairs:
# Ignore order of key/value pairs
memoize('func', key => sub { %@_ });
regardless of what key you specify, it will automatically be prefixed with the full function name and the calling context (L or S).
if the coderef returns CHI::Memoize::NO_MEMOIZE (or NO_MEMOIZE if you import it), this call won't be memoized. this is useful if you have a cache of limited size or if you know certain arguments will yield nondeterministic results. e.g.
memoize('func', key => sub { $is_worth_caching ? @_ : NO_MEMOIZE });
- set and get options β you can pass any of CHI's set options (e.g.
expires_in,expires_variance) or get options (e.g.expire_if,busy_lock). e.g.
# Expire after one hour
memoize('func', expires_in => '1h');
# Expire when a particular condition occurs
memoize('func', expire_if => sub { ... });
- cache options β any remaining options will be passed to the CHI constructor to generate the cache:
# Store in file instead of memory
memoize( 'func', driver => 'File', root_dir => '/path/to/cache' );
# Store in memcached instead of memory
memoize('func', driver => 'Memcached', servers => ["127.0.0.1:11211"]);
unless specified, the namespace is generated from the full name of the function being memoized.
you can also specify an existing cache object:
# Store in memcached instead of memory
my $cache = CHI->new(driver => 'Memcached', servers => ["127.0.0.1:11211"]);
memoize('func', cache => $cache);
π¦ CLONED VS RAW REFERENCES π¦
okay this part is important, listen up. by default CHI, and thus CHI::Memoize, returns a deep clone of the stored value β even when caching in memory. e.g. in this code:
# func returns a list reference
memoize('func');
my $ref1 = func();
my $ref2 = func();
$ref1 and $ref2 will be references to two completely different lists which have the same contained values. more specifically, the value is serialized by Storable on set and deserialized (hence cloned) on get.
the advantage here is that it's safe to modify a reference returned from a memoized function; your modifications won't affect the cached value. π
my $ref1 = func();
push(@$ref1, 3, 4, 5);
my $ref2 = func();
# $ref2 does not have 3, 4, 5
the disadvantage is that it takes extra time to serialize and deserialize the value, and that some values like code references may be more difficult to store. and cloning may not be what you want at all, e.g. if you are returning objects. π¬
alternatively you can use CHI::Driver::RawMemory, which will store raw references the way Memoize does. now, however, any modifications to the contents of a returned reference will affect the cached value. (say it louder for the people in the back)
memoize('func', driver => 'RawMemory');
my $ref1 = func();
push(@$ref1, 3, 4, 5);
my $ref2 = func();
# $ref1 eq $ref2
# $ref2 has 3, 4, 5
π CAVEATS π
the caveats of Memoize apply here as well. to summarize:
- do not memoize a function whose behavior depends on program state other than its own arguments, unless you explicitly capture that state in your computed key. π
- do not memoize a function with side effects, as the side effects won't happen on a cache hit.
- do not memoize a very simple function, as the costs of caching will outweigh the costs of the function itself.
π KNOWN BUGS π
- memoizing a function will affect its call stack and its prototype.
π RELATED MODULES π
a number of modules address a subset of the problems addressed by this module, including:
Memoize::Expireβ pluggable expiration of memoized valuesMemoize::ExpireLRUβ provides LRU expiration forMemoizeMemoize::Memcachedβ use a memcached cache to memoize functions
π«Ά SUPPORT π«Ά
questions and feedback are welcome, and should be directed to the perl-cache mailing list:
http://groups.google.com/group/perl-cache-discuss
bugs and feature requests will be tracked at RT:
http://rt.cpan.org/NoAuth/Bugs.html?Dist=CHI-Memoize
bug-chi-memoize@rt.cpan.org
the latest source code can be browsed and fetched at:
http://github.com/jonswar/perl-chi-memoize
git clone git://github.com/jonswar/perl-chi-memoize.git
π SEE ALSO π
CHI, Memoize
β¨ AUTHOR β¨
Jonathan Swartz <swartz@pobox.com>
π COPYRIGHT AND LICENSE π
this software is copyright (c) 2011 by Jonathan Swartz.
this is free software; you can redistribute it and/or modify it under the same terms as the Perl 5 programming language system itself.
and that's the whole page bestie, tysm for reading π this was perl v5.28.0, dated 2018-10-03, and yes, it's the CHI::Memoize(3pm) page β now go memoize something and slay. π¦β¨π
π¦ where this page comes from
- ubuntu jammy: libchi-memoize-perl 0.07-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- ubuntu noble: libchi-memoize-perl 0.07-2 Β· Artistic-1.0-Perl OR GPL-1.0-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms