const toObject = (one: string, two: string) => ({ one, two });const memoized = memoize(toObject);console.log(memoized('one', 'two'));console.log(memoized('one', 'two')); // pulled from cache// Starting in `4.0.0`, you can compose memoized functions if you want to have multiple types of memoized// versions based on different options.const withUpToFive = memoize(memoized, { maxSize: 5 }); // { maxSize: 5 }const withAsync = memoize(withUpToFive, { async: true }); // { async: true, maxSize: 5 }const withCustomEquals = memoize(withAsync, { isKeyItemEqual: 'deep' }); // { async: true, maxSize: 5, isKeyItemEqual: 'deep' }
NOTE: The original function is the function used in the composition, the composition only applies to the options. In
the example above, withUpToFive does not call memoized, it calls toObject.
Options
async
Identifies the value returned from the method as a Promise, which will result in one of two possible scenarios:
If the promise is resolved, it will fire the hit and update cache events.
If the promise is rejected, it will trigger auto-removal from cache as fire the delete cache event.
NOTE: If you don't want rejections to auto-remove the entry from cache, set async to false (or simply do not set
it), but be aware this will also remove the cache listeners that fire on successful resolution.
expires
The amount of time in milliseconds that you want a computed value to be stored in cache for this method.
TIP: A common usage of this is in tandem with async for AJAX calls, and in that scenario the expected behavior is
usually to have the expires countdown begin upon resolution of the promise. If this is your intended use case, you
should also apply the update configuration option.
forceUpdate
Updates the cache forcibly for a given key when the predicate returns true. This is mainly useful if the function being
memoized has time-based side-effects.
Custom method to compare equality of keys, determining whether to pull from cache or not, by comparing each argument in
order. There are simple string options available for deep / shallow equality comparisons, or you can pass your own
function for custom comparison.
Performs a deep equality comparison of each key item using the deepEqual method from fast-equals.
shallow
Performs a shallow equality comparison using the shallowEqual method from fast-equals.
maxArgs
The maximum number of arguments (starting from the first) used in creating the key for the cache.
const fn = (item1: string, item2: string, item3: string) => item1 + item2 + item3;const memoized = memoize(fn, { maxArgs: 2 });memoized('one', 'two', 'three');memoized('one', 'two', 'four'); // pulls from cache, as the first two args are the same
If maxArgs is combined with either serialize or transformKey, the following order is used:
transform by transformKey (if applicable)
limit by maxArgs
serialize by serialize (if applicable)
maxSize
defaults to 1
The number of values to store in cache, based on a
Least Recently Used basis.
This operates the same as maxSize on memoize.
Serializes the parameters passed into a string and uses this as the key for cache comparison. If a method is passed
instead of a boolean, it is used as a custom serializer.
If serialize is combined with either maxArgs or transformKey, the following order is used:
transform by transformKey (if applicable)
limit by maxArgs (if applicable)
serialize by serialize
NOTE: This is much slower than the default key storage, and usually the same requirements can be meet with
isKeyItemEqual: 'deep', so use at your discretion.
statsName
Name to use as unique identifier for the function when collecting statistics. Applying a statsName will also activate
stats collection for that method.
If your transformed keys require something other than
SameValueZero equality, you can combine
transformKey with isKeyEqual for completely custom key creation and comparison.
If transformKey is combined with either maxArgs or serialize, the following order is used:
transform by transformKey
limit by maxArgs (if applicable)
serialize by serialize (if applicable)
Additional properties
memoized.cache
The cache object that is used internally. This is a highly-optimized structure, but has several methods for manual
cache manipulation.Direct cache manipulation
The cache is an optimized linked list internally, so working with the cache directly is advised against. However, there
are several exposed ways to introspect or manually manipulate the cache based on common use-cases.
memoized.cache.clear()
This will clear all values in the cache, resetting it to an empty state.
This will remove the key based on the provided args from cache. args should be an Array of values, meant to
reflect the arguments passed to the method.
const memoized = memoize((item: { one: string }) => item);const arg = { one: 'one' };memoized(arg);memoized.cache.delete([arg]);// will re-execute, as it is no longer in cachememoized(arg);
NOTE: This will only remove keys that exist in the cache, and will do nothing if the key does not exist.
memoized.cache.get(args)
Returns the value in cache if the key based on args matches, else returns undefined. args should be an Array of
values, meant to reflect the arguments passed to the method.
This will return true if a cache entry exists for the key based on the args passed, else will return false. args
should be an Array of values, meant to reflect the arguments passed to the method.
This will manually add the value at the key based on args in cache if the key does not already exist; if the key
exists, it will update the value. args should be an Array of values, meant to reflect the arguments passed to the
method.
// single parameter is straightforwardconst memoized = memoize((item: string) => item);memoized.cache.set(['one'], 'two');// pulls from cachememoized('one');
memoized.cache.snapshot
The cache is mutated internally for performance reasons, so logging out the cache at a specific step in the workflow
may not give you the information you need. As such, to help with debugging you can request the cache.snapshot, which
provides a well-formed snapshot of the cache:
Hard-coded to true when the function is memoized. This is useful for introspection, to identify if a method has been
memoized or not.
memoized.options
The options passed when creating the memoized method.
Statistics
As-of version 5, you can collect statistics of memoize to determine if your cached methods are effective. To activate
stats collection for a given memoized method, you must provide a statsName.
Start collecting statistics on memoized functions with defined statsName options.
startCollectingStats();
stopCollectingStats()
Stop collecting statistics on memoized functions with defined statsName options.
stopCollectingStats();
Benchmarks
All values provided are the number of operations per second (ops/sec) calculated by
tinybench. Note that underscore, lodash, and ramda do not support
mulitple-parameter memoization (which is where micro-memoize really shines), so they are not included in those
benchmarks.
Benchmarks was performed on an i9 16-core Linux laptop with 64GB of memory using NodeJS version 24.15.0. The default
configuration of each library was tested with a fibonacci calculation based on the following parameters:
NOTE: Not all libraries tested support multiple parameters out of the box, but support the ability to pass a custom
resolver. Because these often need to resolve to a string value,
a common suggestion is to just JSON.stringify the arguments, so that
is what is used when needed.