memoize-one
A memoization library that only caches the result of the most recent arguments.
Rationale
Cache invalidation is hard:
There are only two hard things in Computer Science: cache invalidation and naming things.
Phil Karlton
So keep things simple and just use a cache size of one!
Unlike other memoization libraries, memoize-one
only remembers the latest arguments and result. No need to worry about cache busting mechanisms such as maxAge
, maxSize
, exclusions
and so on which can be prone to memory leaks. memoize-one
simply remembers the last arguments, and if the function is next called with the same arguments then it returns the previous result.
Usage
Standard usage
import memoizeOne from 'memoize-one';
const add = (a, b) => a + b;
const memoizedAdd = memoizeOne(add);
memoizedAdd(1, 2);
memoizedAdd(1, 2);
memoizedAdd(2, 3);
memoizedAdd(2, 3);
memoizedAdd(1, 2);
Custom equality function
You can also pass in a custom function for checking the equality of two items.
import memoizeOne from 'memoize-one';
import deepEqual from 'lodash.isEqual';
const identity = x => x;
const defaultMemoization = memoizeOne(identity);
const customMemoization = memoizeOne(identity, deepEqual);
const result1 = defaultMemoization({foo: 'bar'});
const result2 = defaultMemoization({foo: 'bar'});
result1 === result2
const result3 = customMemoization({foo: 'bar'});
const result4 = customMemoization({foo: 'bar'});
result3 === result4
Equality function type signature
Here is the expected flow type signature for a custom equality function:
type EqualityFn = (a: mixed, b: mixed) => boolean;
Custom equality function with multiple arguments
If the function you want to memoize takes multiple arguments, your custom equality function will be called once for each argument and will be passed each argument's new value and last value.
import memoizeOne from 'memoize-one';
const makeCountObj = (first, second, third) => ({
first: first.count,
second: second.count,
third: third.count,
});
const areCountPropertiesEqual = (newArg, lastArg) => newArg.count === lastArg.count;
const memoizedMakeCountObj = memoizeOne(makeCountObj, areCountPropertiesEqual);
const result1 = memoizedMakeCountObj(
{a: '?', count: 1},
{a: '$', count: 2},
{a: '#', count: 3}
);
const result2 = memoizedMakeCountObj(
{b: null, count: 1},
{b: null, count: 2},
{b: null, count: 3}
);
result1 === result2;
Installation
yarn add memoize-one
npm install memoize-one --save
Module usage
ES6 module
import memoizeOne from 'memoize-one';
CommonJS
If you are in a CommonJS environment (eg Node), then you will need to add .default
to your import:
const memoizeOne = require('memoize-one').default;
this
memoize-one
correctly respects this
control
This library takes special care to maintain, and allow control over the the this
context for both the original function being memoized as well as the returned memoized function. Both the original function and the memoized function's this
context respect all the this
controlling techniques:
- new bindings (
new
) - explicit binding (
call
, apply
, bind
); - implicit binding (call site:
obj.foo()
); - default binding (
window
or undefined
in strict mode
); - fat arrow binding (binding to lexical
this
) - ignored this (pass
null
as this
to explicit binding)
Changes to this
is considered an argument change
Changes to the running context (this
) of a function can result in the function returning a different value even though its arguments have stayed the same:
function getA() {
return this.a;
}
const temp1 = {
a: 20,
};
const temp2 = {
a: 30,
}
getA.call(temp1);
getA.call(temp2);
Therefore, in order to prevent against unexpected results, memoize-one
takes into account the current execution context (this
) of the memoized function. If this
is different to the previous invocation then it is considered a change in argument. further discussion.
Generally this will be of no impact if you are not explicity controlling the this
context of functions you want to memoize with explicit binding or implicit binding. memoize-One
will detect when you are manipulating this
and will then consider the this
context as an argument. If this
changes, it will re-execute the original function even if the arguments have not changed.
Exceptions
What do we do when the wrapped function throws?
If your memoized function throw
s then we will we will not cache the thrown result. If the function is next called with the same arguments then we will re execute the memoized function.
const willThrow = (message) => {
console.log(message);
throw new Error(message);
}
const memoized = memoizeOne(willThrow);
let firstError;
let secondError;
try {
memoized('first message');
} catch (e) {
firstError = e;
}
try {
memoized('first message');
} catch (e) {
secondError = e;
}
console.log(firstError === secondError);
Performance :rocket:
Tiny
memoize-one
is super lightweight at minified and gzipped. (1KB
= 1,024 Bytes
)
Extremely fast
memoize-one
performs better or on par with than other popular memoization libraries for the purpose of remembering the latest invocation.
Results
The comparisions are not exhaustive and are primiarly to show that memoize-one
accomplishes remembering the latest invocation really fast. The benchmarks do not take into account the differences in feature sets, library sizes, parse time, and so on.
Code health :thumbsup: