Sub topic 14
Caching Results with Memoization
This chapter assumes you already know how a closure keeps private state alive between calls, and that you are comfortable passing functions as arguments. Memoization is one direct use of that private state.
What Memoization Does
Memoization is a technique that stores the result of a function call so that a later call with the same input returns the stored result instead of computing it again. It pays off when a function is pure and expensive. A pure function always returns the same output for the same input and has no side effects.
A closure fits this job well. The cache needs to last between calls, so it can't be a local variable of the function being called. It also shouldn't be a global that any code can change. A variable captured by a closure meets both needs.
A Basic Memoize Wrapper
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;
};
}
const square = memoize((n) => n * n);
console.log(square(4)); // 16, computed
console.log(square(4)); // 16, read from cacheEach call to memoize creates a new cache. Only the returned function can reach that cache, so every memoized function keeps its own cache and no outside code can change it.
Memoizing a Recursive Function
Recursive functions benefit the most, but only if the recursive calls go through the memoized version. The code below does that:
const fib = memoize(function (n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
});
console.log(fib(50)); // 12586269025The inner function calls fib, which is the memoized wrapper, so every intermediate result goes into the cache. Without memoization, fib(50) makes billions of calls. With it, each value from 0 to 50 is computed once.
Common Errors
| Mistake | What goes wrong | Fix |
|---|---|---|
| Memoizing an impure function | Results that should change, such as values that depend on time or random numbers, come back stale | Memoize only pure functions |
| Using object arguments as keys | Two equal objects are different `Map` keys, so the cache never hits | Build a key from the values, for example a string |
| Ignoring extra arguments | `memoize` above reads only `n`, so `f(1, 2)` and `f(1, 3)` share one cache entry | Use a key built from all the arguments |
| Recursing through the original function | Only the outer call is cached | Recurse through the memoized wrapper |
To support several primitive arguments, build a key from all of them:
function memoizeMany(fn) {
const cache = new Map();
return function (...args) {
const key = JSON.stringify(args);
if (!cache.has(key)) {
cache.set(key, fn(...args));
}
return cache.get(key);
};
}
const add = memoizeMany((a, b) => a + b);
console.log(add(1, 2)); // 3
console.log(add(1, 3)); // 4Exercise
A developer writes const slowFib = (n) => n < 2 ? n : slowFib(n - 1) + slowFib(n - 2); const fastFib = memoize(slowFib);. Why is fastFib(40) still slow the first time it is called, and how do you fix it?
Show answer
The recursive calls inside slowFib call slowFib itself, not the memoized wrapper, so only the top-level result of 40 is cached. To fix it, define the function so that it recurses through the memoized version, for example const fib = memoize((n) => n < 2 ? n : fib(n - 1) + fib(n - 2));.
Exercise
Why does memoize keep cache inside the closure instead of declaring it as a global variable?
Show answer
The closure gives each memoized function its own cache that lasts between calls and that outside code can't read or change. A global cache would be shared by every function that uses it and could be changed by any code.