The neighbourhood head works out fib(n) on a row of scoreboards: without a memo he works it out every time, with one the board keeps its answer, and an…
Why it matters
The core of many optimisations: useMemo/React.memo, HTTP caches, dynamic programming. Knowing “keep results per argument, but only for pure functions” means knowing when speeding up is safe and when a cache hands back stale answers.
The key idea
Memoization keeps results per argument
Common mistakes
A memoized function gives stale results that never change If the result depends on time, outside data or randomness, the cache hands back stale answers. Only memoize pure functions, or clear/re-key the cache when its data changes.
The cache keeps growing and the app gets laggy Widely varying inputs make the cache balloon (a memory leak). Use a fixed-size LRU or a WeakMap.
Two objects with the same contents count as different arguments to the cache A Map keys on object identity, and JSON.stringify cares about key order. Make the key consistent, or the memo misses.
Try it in this playground
Call fib(5) without a memo 15 calls for one answer: fib(1) alone is asked 5 times.
Turn the memo on, call again Every board is worked out once, then read: 2n − 1 calls.
Slide n to 25, without a memo Hundreds of thousands of real calls: exponential growth.
Call again with the boards already written The memo stays between calls: a bigger fib only reads.