- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Memoization
JavaScript Performance
JavaScript Memoization
Memoization caches a function's results so the same input never does the same work twice.
It trades memory for speed.
It only helps for a pure function, where the same input always gives the same output.
Example
Example
javascript
function memoize(fn) {
const cache = new Map();
return function (n) {
if (cache.has(n)) {
return cache.get(n);
}
const result = fn(n);
cache.set(n, result);
return result;
};
}
let calls = 0;
const double = memoize(function (n) {
calls++;
return n * 2;
});
double(5);
double(5);
double(5);
console.log(calls);