A memoization library which only remembers the latest invocation
A memoization library which only remembers the latest invocation
A memoization library that only caches the result of the most recent arguments.
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. A function memoized with memoize-one simply remembers the last arguments, and if the memoized function is next called with the same arguments then it returns the previous result.
For working with promises, @Kikobeats has built async-memoize-one.
…# yarn
yarn add memoize-one
# npm
npm install memoize-one --saveBy default, we apply our own fast and relatively naive equality function to determine whether the arguments provided to your function are equal. You can see the full code here: are-inputs-equal.ts.
(By default) function arguments are considered equal if:
===) with the previous argument=== and they are both NaN then the two arguments are treated as equalWhat this looks like in practice:
import memoizeOne from 'memoize-one';
// add all numbers provided to the function
const add = (...args = []) =>
args.reduce((current, value) => {
return current + value;
}, 0);
const memoizedAdd = memoizeOne(add);
- there is same amount of arguments
memoizedAdd(1, 2);
// the amount of arguments has changed, so add function is called
memoizedAdd(1, 2, 3);
- new arguments have strict equality (
===) with the previous argument
memoizedAdd(1, 2);
// each argument is `===` to the last argument, so cache is used
memoizedAdd(1, 2);
// second argument has changed, so add function is called again
memoizedAdd(1, 3);
// the first value is not `===` to the previous first value (1 !== 3)
// so add function is called again
memoizedAdd(3, 1);
- [special case] if the arguments are not
===and they are bothNaNthen the argument is treated as equal
memoizedAdd(NaN);
// Even though NaN !== NaN these arguments are
// treated as equal as they are both `NaN`
memoizedAdd(NaN);You can also pass in a custom function for checking the equality of two sets of arguments
const memoized = memoizeOne(fn, isEqual);An equality function should return true if the arguments are equal. If true is returned then the wrapped function will not be called.
Tip: A custom equality function needs to compare Arrays. The newArgs array will be a new reference every time so a simple newArgs === lastArgs will always return false.
Equality functions are not called if the this context of the function has changed (see below).
Here is an example that uses a lodash.isEqual deep equal equality check
lodash.isequalcorrectly handles deep comparing two arrays
import memoizeOne from 'memoize-one';
import isDeepEqual from 'lodash.isequal';
const identity = (x) => x;
const shallowMemoized = memoizeOne(identity);
const deepMemoized = memoizeOne(identity, isDeepEqual);
const result1 = shallowMemoized({ foo: 'bar' });
const result2 = shallowMemoized({ foo: 'bar' });
result1 === result2; // false - different object reference
const result3 = deepMemoized({ foo: 'bar' });
const result4 = deepMemoized({ foo: 'bar' });
result3 === result4; // true - arguments are deep equalThe equality function needs to conform to the EqualityFn type:
// TFunc is the function being memoized
type EqualityFn<TFunc extends (...args: any[]) => any> = (
newArgs: Parameters<TFunc>,
lastArgs: Parameters<TFunc>,
) => boolean;
// You can import this type
import type { EqualityFn } from 'memoize-one';The EqualityFn type allows you to create equality functions that are extremely typesafe. You are welcome to provide your own less type safe equality functions.
Here are some examples of equality functions which are ordered by most type safe, to least type safe:
Example equality function types…thismemoize-one correctly respects this controlThis 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)call, apply, bind);obj.foo());window or undefined in strict mode);this)null as this to explicit binding)this is considered an argument changeChanges 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); // 20
getA.call(temp2); // 30Therefore, 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.
A .clear() property is added to memoized functions to allow you to clear it's memoization cache.
This is helpful if you want to:
import memoizeOne from 'memoize-one';
function add(a: number, b: number): number {
return a + b;
}
const memoizedAdd = memoizeOne(add);
// first call - not memoized
const first = memoizedAdd(1, 2);
// second call - cache hit (result function not called)
const second = memoizedAdd(1, 2);
// clearing memoization cache
memoizedAdd.clear();
// third call - not memoized (cache was cleared)
const third = memoizedAdd(1, 2);throwsThere is no caching when your result function throws
If your result function throws then the memoized function will also throw. The throw will not break the memoized functions existing argument cache. It means the memoized function will pretend like it was never called with arguments that made it throw.
…Functions memoized with memoize-one do not preserve any properties on the function object.
This behaviour is correctly reflected in the TypeScript types
import memoizeOne from 'memoize-one';
function add(a, b) {
return a + b;
}
add.hello = 'hi';
console.log(typeof add.hello); // string
const memoized = memoizeOne(add);
// hello property on the `add` was not preserved
console.log(typeof memoized.hello); // undefinedIf you feel strongly that
memoize-oneshould preserve function properties, please raise an issue. This decision was made in order to keepmemoize-oneas light as possible.
For now, the .length property of a function is not preserved on the memoized function
import memoizeOne from 'memoize-one';
function add(a, b) {
return a + b;
}
console.log(add.length); // 2
const memoized = memoizeOne(add);
console.log(memoized.length); // 0There is no (great) way to correctly set the .length property of the memoized function while also supporting ie11. Once we remove ie11 support then we plan on setting the .length property of the memoized function to match the original function
typeThe resulting function you get back from memoize-one has almost the same type as the function that you are memoizing
declare type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = {
clear: () => void;
(this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>;
};.clear() function property addedTFunc as not carried overYou are welcome to use the MemoizedFn generic directly from memoize-one if you like:
import memoize, { MemoizedFn } from 'memoize-one';
import isDeepEqual from 'lodash.isequal';
import { expectTypeOf } from 'expect-type';
// Takes any function: TFunc, and returns a Memoized<TFunc>
function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc): MemoizedFn<TFunc> {
return memoize(fn, isDeepEqual);
}
function add(first: number, second: number): number {
return first + second;
}
const memoized = withDeepEqual(add);
expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();In this specific example, this type would have been correctly inferred too
import memoize, { MemoizedFn } from 'memoize-one';
import isDeepEqual from 'lodash.isequal';
import { expectTypeOf } from 'expect-type';
// return type of MemoizedFn<TFunc> is inferred
function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc) {
return memoize(fn, isDeepEqual);
}
function add(first: number, second: number): number {
return first + second;
}
const memoized = withDeepEqual(add);
// type test still passes
expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();memoize-one is super lightweight at minified and gzipped. (1KB = 1,024 Bytes)
memoize-one performs better or on par with than other popular memoization libraries for the purpose of remembering the latest invocation.
The comparisons are not exhaustive and are primarily to show that memoize-one accomplishes remembering the latest invocation really fast. There is variability between runs. The benchmarks do not take into account the differences in feature sets, library sizes, parse time, and so on.
node version 16.11.1
You can run this test in the repo by:
"type": "module" to the package.json (why is things so hard)yarn perf:library-comparisonno arguments
| Position | Library | Operations per second |
|---|---|---|
| 1 | memoize-one | 80,112,981 |
| 2 | moize | 72,885,631 |
| 3 | memoizee | 35,550,009 |
| 4 | m |
No open issues yet, or sync has not completed.