Sub topic 14
Memoization: Caching Pure Results
This chapter assumes you know pure functions, closures, and higher-order functions from earlier chapters. You should also be comfortable with Map and with recursion in JavaScript.
Memoization caches the result of a function call. When the same arguments come in again, the function returns the stored answer and skips the computation. This is only safe when the function is pure: same input, same output, no side effects. If the function is pure, a cached answer and a freshly computed one are indistinguishable.
The cost of repeated work
A naive recursive Fibonacci solves the same subproblems again and again. fib(30) calls fib(28) twice, fib(27) three times, and so on.
let calls = 0;
const slowFib = (n) => {
calls += 1;
return n < 2 ? n : slowFib(n - 1) + slowFib(n - 2);
};
console.log(slowFib(30)); // 832040
console.log(calls); // 2692537That is nearly 2.7 million calls to produce 31 distinct answers.
A memoize helper
A closure gives the wrapper its own private cache:
const memoize = (fn) => {
const cache = new Map();
return (n) => {
if (!cache.has(n)) cache.set(n, fn(n));
return cache.get(n);
};
};
let memoCalls = 0;
const fib = memoize((n) => {
memoCalls += 1;
return n < 2 ? n : fib(n - 1) + fib(n - 2);
});
console.log(fib(30)); // 832040
console.log(memoCalls); // 31
console.log(fib(50)); // 12586269025Each value from 0 to 30 is computed once, which turns exponential time into linear time. The code checks with cache.has instead of testing the stored value for truthiness, so results such as 0 or undefined are cached correctly.
Multiple arguments
A Map compares keys by identity, so [2, 10] and another [2, 10] count as different keys. For multiple arguments, build a key yourself:
const memoizeWith = (keyFn, fn) => {
const cache = new Map();
return (...args) => {
const key = keyFn(...args);
if (!cache.has(key)) cache.set(key, fn(...args));
return cache.get(key);
};
};
const power = memoizeWith((b, e) => `${b},${e}`, (b, e) => b ** e);
console.log(power(2, 10)); // 1024
console.log(power(2, 10)); // 1024, from cacheCommon errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Memoizing an impure function | Stale results, such as an old `Date.now()` value or outdated fetched data | Memoize only pure functions |
| Recursive calls bypass the wrapper | Only the outer call is cached | Recurse through the memoized name |
| Object arguments as keys | Equal-looking objects miss the cache | Derive a key, or use `WeakMap` for identity-based caching |
| Unbounded cache | Memory grows forever in long-running processes | Cap the size (LRU) or scope the cache's lifetime |
Exercise
A developer writes const fastFib = memoize(slowFib); using slowFib from above. Why is fastFib(35) the first time barely faster than slowFib(35)?
Show answer
The recursive calls inside slowFib call slowFib directly, not fastFib, so only the outermost result gets cached. The function must recurse through the memoized reference, as fib does in the chapter, for the subproblems to be cached.
Exercise
Why does memoize use cache.has(n) rather than if (cache.get(n))?
Show answer
A truthiness check treats cached falsy results like 0 (for example fib(0)) as missing. Those values would be recomputed on every call.