Gathering detailed insights and metrics for memoize-one
Gathering detailed insights and metrics for memoize-one
Gathering detailed insights and metrics for memoize-one
Gathering detailed insights and metrics for memoize-one
kashe
Stateless weak memoization replacement for reselect and memoize-one
@essentials/memoize-one
A memoization algorithm that only caches the result of the latest set of arguments, where argument equality is determined via a provided equality function.
async-memoize-one
memoize the last result, in async way
lazy-memoize-one
A `memoize-one` wrapper that resolves the latest invocation asynchronously
A memoization library which only remembers the latest invocation
npm install memoize-one
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
2,947 Stars
236 Commits
79 Forks
13 Watching
17 Branches
15 Contributors
Updated on 25 Nov 2024
Minified
Minified + Gzipped
TypeScript (83.27%)
JavaScript (16.73%)
Cumulative downloads
Total Downloads
Last day
-3.3%
2,389,450
Compared to previous day
Last week
4.5%
12,584,296
Compared to previous week
Last month
12.3%
51,599,282
Compared to previous month
Last year
12.3%
559,827,883
Compared to previous year
36
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.
1// memoize-one uses the default import 2import memoizeOne from 'memoize-one'; 3 4function add(a, b) { 5 return a + b; 6} 7const memoizedAdd = memoizeOne(add); 8 9memoizedAdd(1, 2); 10// add function: is called 11// [new value returned: 3] 12 13memoizedAdd(1, 2); 14// add function: not called 15// [cached result is returned: 3] 16 17memoizedAdd(2, 3); 18// add function: is called 19// [new value returned: 5] 20 21memoizedAdd(2, 3); 22// add function: not called 23// [cached result is returned: 5] 24 25memoizedAdd(1, 2); 26// add function: is called 27// [new value returned: 3] 28// 👇 29// While the result of `add(1, 2)` was previously cached 30// `(1, 2)` was not the *latest* arguments (the last call was `(2, 3)`) 31// so the previous cached result of `(1, 3)` was lost
1# yarn 2yarn add memoize-one 3 4# npm 5npm install memoize-one --save
By 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:
1import memoizeOne from 'memoize-one'; 2 3// add all numbers provided to the function 4const add = (...args = []) => 5 args.reduce((current, value) => { 6 return current + value; 7 }, 0); 8const memoizedAdd = memoizeOne(add);
- there is same amount of arguments
1memoizedAdd(1, 2); 2// the amount of arguments has changed, so add function is called 3memoizedAdd(1, 2, 3);
- new arguments have strict equality (
===
) with the previous argument
1memoizedAdd(1, 2); 2// each argument is `===` to the last argument, so cache is used 3memoizedAdd(1, 2); 4// second argument has changed, so add function is called again 5memoizedAdd(1, 3); 6// the first value is not `===` to the previous first value (1 !== 3) 7// so add function is called again 8memoizedAdd(3, 1);
- [special case] if the arguments are not
===
and they are bothNaN
then the argument is treated as equal
1memoizedAdd(NaN); 2// Even though NaN !== NaN these arguments are 3// treated as equal as they are both `NaN` 4memoizedAdd(NaN);
You can also pass in a custom function for checking the equality of two sets of arguments
1const 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.isequal
correctly handles deep comparing two arrays
1import memoizeOne from 'memoize-one'; 2import isDeepEqual from 'lodash.isequal'; 3 4const identity = (x) => x; 5 6const shallowMemoized = memoizeOne(identity); 7const deepMemoized = memoizeOne(identity, isDeepEqual); 8 9const result1 = shallowMemoized({ foo: 'bar' }); 10const result2 = shallowMemoized({ foo: 'bar' }); 11 12result1 === result2; // false - different object reference 13 14const result3 = deepMemoized({ foo: 'bar' }); 15const result4 = deepMemoized({ foo: 'bar' }); 16 17result3 === result4; // true - arguments are deep equal
The equality function needs to conform to the EqualityFn
type
:
1// TFunc is the function being memoized 2type EqualityFn<TFunc extends (...args: any[]) => any> = ( 3 newArgs: Parameters<TFunc>, 4 lastArgs: Parameters<TFunc>, 5) => boolean; 6 7// You can import this type 8import 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:
1// the function we are going to memoize 2function add(first: number, second: number): number { 3 return first + second; 4} 5 6// Some options for our equality function 7// ↑ stronger types 8// ↓ weaker types 9 10// ✅ exact parameters of `add` 11{ 12 const isEqual = function (first: Parameters<typeof add>, second: Parameters<typeof add>) { 13 return true; 14 }; 15 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 16} 17 18// ✅ tuple of the correct types 19{ 20 const isEqual = function (first: [number, number], second: [number, number]) { 21 return true; 22 }; 23 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 24} 25 26// ❌ tuple of incorrect types 27{ 28 const isEqual = function (first: [number, string], second: [number, number]) { 29 return true; 30 }; 31 expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); 32} 33 34// ✅ array of the correct types 35{ 36 const isEqual = function (first: number[], second: number[]) { 37 return true; 38 }; 39 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 40} 41 42// ❌ array of incorrect types 43{ 44 const isEqual = function (first: string[], second: number[]) { 45 return true; 46 }; 47 expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); 48} 49 50// ✅ tuple of 'unknown' 51{ 52 const isEqual = function (first: [unknown, unknown], second: [unknown, unknown]) { 53 return true; 54 }; 55 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 56} 57 58// ❌ tuple of 'unknown' of incorrect length 59{ 60 const isEqual = function (first: [unknown, unknown, unknown], second: [unknown, unknown]) { 61 return true; 62 }; 63 expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); 64} 65 66// ✅ array of 'unknown' 67{ 68 const isEqual = function (first: unknown[], second: unknown[]) { 69 return true; 70 }; 71 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 72} 73 74// ✅ spread of 'unknown' 75{ 76 const isEqual = function (...first: unknown[]) { 77 return !!first; 78 }; 79 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 80} 81 82// ✅ tuple of 'any' 83{ 84 const isEqual = function (first: [any, any], second: [any, any]) { 85 return true; 86 }; 87 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 88} 89 90// ❌ tuple of 'any' or incorrect size 91{ 92 const isEqual = function (first: [any, any, any], second: [any, any]) { 93 return true; 94 }; 95 expectTypeOf<typeof isEqual>().not.toMatchTypeOf<EqualityFn<typeof add>>(); 96} 97 98// ✅ array of 'any' 99{ 100 const isEqual = function (first: any[], second: any[]) { 101 return true; 102 }; 103 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 104} 105 106// ✅ two arguments of type any 107{ 108 const isEqual = function (first: any, second: any) { 109 return true; 110 }; 111 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 112} 113 114// ✅ a single argument of type any 115{ 116 const isEqual = function (first: any) { 117 return true; 118 }; 119 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 120} 121 122// ✅ spread of any type 123{ 124 const isEqual = function (...first: any[]) { 125 return true; 126 }; 127 expectTypeOf<typeof isEqual>().toMatchTypeOf<EqualityFn<typeof add>>(); 128}
this
memoize-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:
1function getA() { 2 return this.a; 3} 4 5const temp1 = { 6 a: 20, 7}; 8const temp2 = { 9 a: 30, 10}; 11 12getA.call(temp1); // 20 13getA.call(temp2); // 30
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.
A .clear()
property is added to memoized functions to allow you to clear it's memoization cache.
This is helpful if you want to:
1import memoizeOne from 'memoize-one';
2
3function add(a: number, b: number): number {
4 return a + b;
5}
6
7const memoizedAdd = memoizeOne(add);
8
9// first call - not memoized
10const first = memoizedAdd(1, 2);
11
12// second call - cache hit (result function not called)
13const second = memoizedAdd(1, 2);
14
15// 👋 clearing memoization cache
16memoizedAdd.clear();
17
18// third call - not memoized (cache was cleared)
19const third = memoizedAdd(1, 2);
throw
sThere is no caching when your result function throws
If your result function throw
s 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
.
1const canThrow = (name: string) => { 2 console.log('called'); 3 if (name === 'throw') { 4 throw new Error(name); 5 } 6 return { name }; 7}; 8 9const memoized = memoizeOne(canThrow); 10 11const value1 = memoized('Alex'); 12// result function called: console.log => 'called' 13 14const value2 = memoized('Alex'); 15// result function not called (cache hit) 16 17console.log(value1 === value2); 18// console.log => true 19 20try { 21 memoized('throw'); 22 // console.log => 'called' 23} catch (e) { 24 firstError = e; 25} 26 27try { 28 memoized('throw'); 29 // console.log => 'called' 30 // the result function was called again even though it was called twice 31 // with the 'throw' string 32} catch (e) { 33 secondError = e; 34} 35 36console.log(firstError !== secondError); 37// console.log => true 38 39const value3 = memoized('Alex'); 40// result function not called as the original memoization cache has not been busted 41 42console.log(value1 === value3); 43// console.log => true
Functions memoized with memoize-one
do not preserve any properties on the function object.
This behaviour is correctly reflected in the TypeScript types
1import memoizeOne from 'memoize-one'; 2 3function add(a, b) { 4 return a + b; 5} 6add.hello = 'hi'; 7 8console.log(typeof add.hello); // string 9 10const memoized = memoizeOne(add); 11 12// hello property on the `add` was not preserved 13console.log(typeof memoized.hello); // undefined
If you feel strongly that
memoize-one
should preserve function properties, please raise an issue. This decision was made in order to keepmemoize-one
as light as possible.
For now, the .length
property of a function is not preserved on the memoized function
1import memoizeOne from 'memoize-one'; 2 3function add(a, b) { 4 return a + b; 5} 6 7console.log(add.length); // 2 8 9const memoized = memoizeOne(add); 10 11console.log(memoized.length); // 0
There 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
type
The resulting function you get back from memoize-one
has almost the same type
as the function that you are memoizing
1declare type MemoizedFn<TFunc extends (this: any, ...args: any[]) => any> = { 2 clear: () => void; 3 (this: ThisParameterType<TFunc>, ...args: Parameters<TFunc>): ReturnType<TFunc>; 4};
.clear()
function property addedTFunc
as not carried overYou are welcome to use the MemoizedFn
generic directly from memoize-one
if you like:
1import memoize, { MemoizedFn } from 'memoize-one';
2import isDeepEqual from 'lodash.isequal';
3import { expectTypeOf } from 'expect-type';
4
5// Takes any function: TFunc, and returns a Memoized<TFunc>
6function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc): MemoizedFn<TFunc> {
7 return memoize(fn, isDeepEqual);
8}
9
10function add(first: number, second: number): number {
11 return first + second;
12}
13
14const memoized = withDeepEqual(add);
15
16expectTypeOf<typeof memoized>().toEqualTypeOf<MemoizedFn<typeof add>>();
In this specific example, this type would have been correctly inferred too
1import memoize, { MemoizedFn } from 'memoize-one';
2import isDeepEqual from 'lodash.isequal';
3import { expectTypeOf } from 'expect-type';
4
5// return type of MemoizedFn<TFunc> is inferred
6function withDeepEqual<TFunc extends (...args: any[]) => any>(fn: TFunc) {
7 return memoize(fn, isDeepEqual);
8}
9
10function add(first: number, second: number): number {
11 return first + second;
12}
13
14const memoized = withDeepEqual(add);
15
16// type test still passes
17expectTypeOf<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-comparison
no arguments
Position | Library | Operations per second |
---|---|---|
1 | memoize-one | 80,112,981 |
2 | moize | 72,885,631 |
3 | memoizee | 35,550,009 |
4 | mem (JSON.stringify strategy) | 4,610,532 |
5 | lodash.memoize (JSON.stringify key resolver) | 3,708,945 |
6 | no memoization | 505 |
7 | fast-memoize | 504 |
single primitive argument
Position | Library | Operations per second |
---|---|---|
1 | fast-memoize | 45,482,711 |
2 | moize | 34,810,659 |
3 | memoize-one | 29,030,828 |
4 | memoizee | 23,467,065 |
5 | mem (JSON.stringify strategy) | 3,985,223 |
6 | lodash.memoize (JSON.stringify key resolver) | 3,369,297 |
7 | no memoization | 507 |
single complex argument
Position | Library | Operations per second |
---|---|---|
1 | moize | 27,660,856 |
2 | memoize-one | 22,407,916 |
3 | memoizee | 19,546,835 |
4 | mem (JSON.stringify strategy) | 2,068,038 |
5 | lodash.memoize (JSON.stringify key resolver) | 1,911,335 |
6 | fast-memoize | 1,633,855 |
7 | no memoization | 504 |
multiple primitive arguments
Position | Library | Operations per second |
---|---|---|
1 | moize | 22,366,497 |
2 | memoize-one | 17,241,995 |
3 | memoizee | 9,789,442 |
4 | mem (JSON.stringify strategy) | 3,065,328 |
5 | lodash.memoize (JSON.stringify key resolver) | 2,663,599 |
6 | fast-memoize | 1,219,548 |
7 | no memoization | 504 |
multiple complex arguments
Position | Library | Operations per second |
---|---|---|
1 | moize | 21,788,081 |
2 | memoize-one | 17,321,248 |
3 | memoizee | 9,595,420 |
4 | lodash.memoize (JSON.stringify key resolver) | 873,283 |
5 | mem (JSON.stringify strategy) | 850,779 |
6 | fast-memoize | 687,863 |
7 | no memoization | 504 |
multiple complex arguments (spreading arguments)
Position | Library | Operations per second |
---|---|---|
1 | moize | 21,701,537 |
2 | memoizee | 19,463,942 |
3 | memoize-one | 17,027,544 |
4 | lodash.memoize (JSON.stringify key resolver) | 887,816 |
5 | mem (JSON.stringify strategy) | 849,244 |
6 | fast-memoize | 691,512 |
7 | no memoization | 504 |
Typescript
Typescript
and flow
type systemsNo vulnerabilities found.
Reason
no binaries found in the repo
Reason
no dangerous workflow patterns detected
Reason
license file detected
Details
Reason
0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0
Reason
Found 0/5 approved changesets -- score normalized to 0
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
Reason
project is not fuzzed
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Reason
26 existing vulnerabilities detected
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More