Sub topic 14
Memoization: Caching Pure Results
Memoization means storing the result of a function call and returning that stored result the next time the function receives the same arguments. This chapter assumes you know closures, pure functions, and recursion from earlier chapters, and that you can use Map and run code in Node.js. Memoization depends on all three of those ideas. The cache lives in a closure. The function must be pure, or the cached answer can be wrong. Recursion produces the repeated subproblems that make caching worth doing.
Why repeated work happens
A naive recursive Fibonacci function computes the same values again and again. To get fib(5), it computes fib(3) twice and fib(2) three times, and the repetition grows exponentially as n grows.
let calls = 0;
const slowFib = (n) => {
calls += 1;
return n < 2 ? n : slowFib(n - 1) + slowFib(n - 2);
};
console.log(slowFib(25)); // 75025
console.log(calls); // 242785There are only 26 distinct inputs between 0 and 25, but the function ran 242,785 times. Each repeated call does the same work as the first one, so caching those results removes almost all of it.
A basic memoize helper
A memoizing wrapper is a higher-order function. It takes a function and returns a new function that checks a cache before doing any work.
const memoize = (fn) => {
const cache = new Map();
return (n) => {
if (!cache.has(n)) cache.set(n, fn(n));
return cache.get(n);
};
};
let fastCalls = 0;
const fib = memoize((n) => {
fastCalls += 1;
return n < 2 ? n : fib(n - 1) + fib(n - 2);
});
console.log(fib(50)); // 12586269025
console.log(fastCalls); // 51Each input from 0 to 50 is computed once, which makes the running time linear. The cache variable is private. Only the returned function can reach it, because it closed over cache when memoize ran.
Use `has`, not a truthiness check
A shortcut such as cache.get(n) || compute() breaks for results like 0, '', false, or undefined. These values are falsy, so the function recomputes them on every call. In the Fibonacci example, fib(0) returns 0. Checking with cache.has(n) treats every stored value as a hit.
Gotcha: memoizing from the outside
Wrapping an existing recursive function does not memoize its recursive calls.
let innerCalls = 0;
const plainFib = (n) => {
innerCalls += 1;
return n < 2 ? n : plainFib(n - 1) + plainFib(n - 2);
};
const wrapped = memoize(plainFib);
console.log(wrapped(25)); // 75025
console.log(innerCalls); // 242785, no improvement on the first call
console.log(wrapped(25)); // 75025, instant: the top-level result is cached
console.log(innerCalls); // 242785plainFib calls itself by name. That name points to the unwrapped version, so only the outermost call goes through the cache. To memoize the subproblems, the recursive calls must go through the memoized binding, as fib does in the previous example.
Pure functions only
Memoization assumes that the same input always produces the same output. That property is referential transparency. If a function reads the clock, random numbers, a global variable, or a database, the cached value becomes wrong without any error to tell you.
const memoize = (fn) => {
const cache = new Map();
return (n) => {
if (!cache.has(n)) cache.set(n, fn(n));
return cache.get(n);
};
};
let taxRate = 0.2;
const priceWithTax = memoize((price) => price * (1 + taxRate));
console.log(priceWithTax(100)); // 120
taxRate = 0.25;
console.log(priceWithTax(100)); // 120, stale: should be 125Side effects also disappear on cache hits. If a memoized function logs a message or sends a request, it does so only on the first call.
Multiple arguments and cache keys
Map compares keys with SameValueZero. That works for primitives, but a call such as f(1, 2) has two arguments and a Map key is a single value. A common solution is to let the caller supply a key function:
const memoizeWith = (keyFn, fn) => {
const cache = new Map();
return (...args) => {
const key = keyFn(...args);
if (cache.has(key)) return cache.get(key);
const result = fn(...args);
cache.set(key, result);
return result;
};
};
// Number of right/down paths through an r-by-c grid
const gridPaths = memoizeWith(
(r, c) => `${r},${c}`,
(r, c) => (r === 0 || c === 0 ? 1 : gridPaths(r - 1, c) + gridPaths(r, c - 1))
);
console.log(gridPaths(16, 16)); // 601080390The key function determines whether the cache is correct. Each key strategy fails in its own way:
| Key strategy | Works well for | Failure mode |
|---|---|---|
| Single primitive argument | Numbers, strings | Cannot handle more than one argument |
| Joined string such as `` `${a},${b}` `` | A few primitive arguments | Collisions if values can contain the separator; `1` and `'1'` produce the same key |
| `JSON.stringify(args)` | Plain data | Slow for large inputs; `{a,b}` and `{b,a}` produce different keys; drops functions and `undefined` |
| Object identity (`Map` or `WeakMap`) | Immutable objects | Equal copies miss the cache; mutated objects return stale results |
Object arguments and WeakMap
When the argument is an object, you can key the cache on the object's reference. A WeakMap holds its keys weakly. When nothing else references an object, the garbage collector can remove both the object and its cache entry, so the cache does not leak memory.
const memoizeByRef = (fn) => {
const cache = new WeakMap();
return (obj) => {
if (!cache.has(obj)) cache.set(obj, fn(obj));
return cache.get(obj);
};
};
let totalCalls = 0;
const orderTotal = memoizeByRef((order) => {
totalCalls += 1;
return order.items.reduce((sum, item) => sum + item.price, 0);
});
const order = { items: [{ price: 10 }, { price: 5 }] };
console.log(orderTotal(order)); // 15
console.log(orderTotal(order)); // 15
console.log(totalCalls); // 1
const updated = { ...order, items: [...order.items, { price: 7 }] };
console.log(orderTotal(updated)); // 22
console.log(totalCalls); // 2This approach depends on immutability. When data is updated by creating a new object, a new reference means the data changed, and the old entry stays valid. If code pushed to order.items directly, orderTotal(order) would keep returning 15. React's useMemo and selector libraries such as Reselect rely on this same reference-equality assumption.
Bounding the cache
A Map-based cache never forgets anything. If a memoized function runs on a server with user-controlled inputs, the cache grows without limit. A least-recently-used (LRU) cache sets a maximum size. Because Map keeps insertion order, a basic LRU cache takes only a few lines:
const memoizeLRU = (fn, limit = 100) => {
const cache = new Map();
return (key) => {
if (cache.has(key)) {
const value = cache.get(key);
cache.delete(key); // move to the most-recent position
cache.set(key, value);
return value;
}
const value = fn(key);
cache.set(key, value);
if (cache.size > limit) cache.delete(cache.keys().next().value); // evict oldest
return value;
};
};
const square = memoizeLRU((x) => x * x, 2);
square(1); square(2); square(1); square(3); // 2 is evicted, 1 and 3 remain
console.log(square(3)); // 9Memoizing async functions
To memoize an async function, cache the promise instead of the resolved value. Concurrent callers then share one in-flight request. If the request fails, delete the entry so that the cache does not keep the failure.
const memoizeAsync = (fn) => {
const cache = new Map();
return (key) => {
if (!cache.has(key)) {
const promise = fn(key).catch((err) => {
cache.delete(key);
throw err;
});
cache.set(key, promise);
}
return cache.get(key);
};
};
let requests = 0;
const fetchUser = memoizeAsync(async (id) => {
requests += 1;
await new Promise((resolve) => setTimeout(resolve, 50));
return { id, name: `User ${id}` };
});
Promise.all([fetchUser(1), fetchUser(1), fetchUser(2)]).then((users) => {
console.log(users.map((u) => u.name)); // [ 'User 1', 'User 1', 'User 2' ]
console.log(requests); // 2
});Network data is not pure, because the server's answer can change. In production, add an expiry time to each entry or use a library that handles it, such as TanStack Query.
When memoization costs more than it saves
Each memoized call computes a key, performs a lookup, and keeps a value in memory. Memoization helps when a function is expensive and is called repeatedly with a small set of inputs. It slows code down when a function is cheap (such as x * 2), when inputs rarely repeat, or when computing the key costs as much as the work itself, as with JSON.stringify on a large array. Measure before and after adding it.
Exercise
A teammate writes const area = memoize((rect) => rect.w * rect.h) using the single-argument Map-based memoize, then calls area({ w: 2, h: 3 }) in a render loop that runs 1,000 times. The function's call counter shows 1,000 calls. Why, and what are two ways to fix it?
Show answer
Each call passes a new object literal. Map keys compare objects by reference, so every call misses the cache, and every new object is also stored in the Map, which leaks memory. Fix 1: use a key function on the values, for example memoizeWith((r) => ${r.w}x${r.h}, ...). Fix 2: create the rectangle object once outside the loop and use a WeakMap-based memoize keyed on that reference. Since this computation is cheap, a third option is to drop memoization entirely.
Exercise
Write a memoized countWays(n) that returns how many ways you can climb n stairs taking 1 or 2 steps at a time (countWays(0) = 1, countWays(1) = 1). Make sure the recursive calls hit the cache. What does countWays(40) return?
Show answer
const countWays = memoize((n) => (n < 2 ? 1 : countWays(n - 1) + countWays(n - 2))); The recursion goes through the memoized binding countWays, not an inner unwrapped function. countWays(40) returns 165580141, which is fib(41).
Exercise
In memoizeAsync, what would go wrong if the .catch handler that deletes the key were removed?
Show answer
A rejected promise would stay in the cache permanently. Every later call with that key would receive the same rejection immediately, and the function would never retry, even after the network or server recovered.