Memoization
Intermediate · 9 min · code in PHP, JavaScript, Java and Go
Where you will meet this in real life
Memoization means saving the answer to a calculation the first time you do it, so the next time the same question comes up you just look it up. It turns repeated work into a quick lookup. It is one of the easiest ways to make a slow function fast.
Practical use cases
- Web app: React component that recalculates on every render. A dashboard page shows a sales summary computed from 50,000 rows. Every time the user types in an unrelated search box, React re-renders and recalculates it, making typing laggy. Wrapping the calculation in useMemo saves the result and reuses it until the rows really change, so typing becomes smooth.
- Web app: Shipping cost or tax lookup. A checkout calls a slow function to work out the tax for a pincode and cart value, and many customers share the same pincode. Saving results by pincode and amount means only the first customer pays the cost. Everyone else gets the answer straight from memory. On a busy sale day with thousands of orders going to the same few cities, this one change can remove most of the slow calls and keep the checkout page quick.
- System: Compilers and game engines. A game engine saves results of expensive path or physics calculations that repeat every frame. A compiler saves the result of analysing the same piece of code several times. In both cases a small lookup table stops the same work from repeating.
The story: Raju and the Chalk Slate
Raju's chai stall has a famous problem: customers keep asking, "How much for 7 cups for the whole wedding party?" and every time Raju does the whole calculation again from scratch, slowly adding on his fingers. By afternoon he has answered the same question twenty times and his tea is cold.
Mira, watching from a stool, had an idea. "Hang a small slate on the wall. Each time you work out an answer, chalk it down. Next time someone asks, look at the slate first." Raju grumbled, but he tried it. The first time "7 cups" cost him a minute. The second time it cost him one glance.
The trick got even better. To work out "7 cups" he needed the answers for 6 cups and 5 cups. Those were already on the slate from earlier customers! So big questions got answered by reading small answers that had been chalked up before.
That slate is called memoization (say it "mem-o-ization", like a memo or a note to yourself). You keep the normal top-down thinking ("to answer the big thing I need the smaller things"), but you remember every answer you find so nothing is ever calculated twice.
How to spot this problem, and where you need it
Your code answers the same question again and again with the same inputs, and each time it does all the work from scratch, so it gets slow as more calls pile up.
Signs you need it
- A recursive function calls itself with the same arguments many times, and doubling the input makes it far slower than twice as slow.
- Profiling shows one function called thousands of times with only a few different inputs.
- A page lags because the same heavy calculation runs on every re-render or every request.
Where to use it in a project
- Heavy computed values in React components, using useMemo or a selector library.
- Server-side calculations repeated for the same inputs, such as tax, shipping or discount rules, held in an array or Redis cache.
The solution
Create a small lookup table, such as an object or associative array, keyed by the inputs. At the start of the function, check whether the key is already in the table; if so, return the saved answer. Otherwise, do the calculation, store the result under the key, and then return it. Each distinct question is worked out only once, no matter how often it is asked.
Payoff: Before: a recursive calculation taking over a minute for input 45. After: the same answer in a few milliseconds with about 45 saved results.
Explain it like I am 8
Imagine your teacher asks the whole class the same question again and again. The first time you do the sum slowly. Then you write the answer on the inside of your hand. Next time you just peek at your hand. Memoization is that: peek before you think.
How it works, step by step
- Write the plain recursive answer first: a function that solves a big question by asking smaller ones.
- Make a notebook (an array or map) that remembers answers, keyed by the question (for example the number
n). - Peek first: at the top of the function, if the question is already in the notebook, return that answer right away.
- Otherwise compute it from the smaller questions (recursion), then write the answer in the notebook before returning.
- Every different question is now worked out only once, so a slow exploding recursion becomes quick.
The code in four languages
PHP
<?php
// Memoization: recursion + a notebook that remembers answers.
function fibMemo(int $n, array &$memo, int &$work): int {
if (isset($memo[$n])) return $memo[$n]; // peek first: already in the notebook?
$work++; // count real computations
if ($n < 2) return $memo[$n] = $n; // base cases
// Compute from smaller questions, then write the answer down.
return $memo[$n] = fibMemo($n - 1, $memo, $work) + fibMemo($n - 2, $memo, $work);
}
$memo = [];
$work = 0;
echo "fib(40) = ", fibMemo(40, $memo, $work), "\n";
echo "real computations: ", $work, "\n"; // only 41, plain recursion needs ~330 million callsJavaScript
// Memoization: recursion + a notebook that remembers answers.
function fibMemo(n, memo, stats) {
if (memo.has(n)) return memo.get(n); // peek first: already in the notebook?
stats.work++; // count real computations
if (n < 2) { memo.set(n, n); return n; } // base cases
// Compute from smaller questions, then write the answer down.
const answer = fibMemo(n - 1, memo, stats) + fibMemo(n - 2, memo, stats);
memo.set(n, answer);
return answer;
}
const stats = { work: 0 };
console.log("fib(40) =", fibMemo(40, new Map(), stats));
console.log("real computations:", stats.work); // only 41, plain recursion needs ~330 million callsJava
import java.util.*;
public class Main {
static int work = 0; // count real computations
// Memoization: recursion + a notebook that remembers answers.
static long fibMemo(int n, Map<Integer, Long> memo) {
if (memo.containsKey(n)) return memo.get(n); // peek first: already in the notebook?
work++;
if (n < 2) { memo.put(n, (long) n); return n; } // base cases
// Compute from smaller questions, then write the answer down.
long answer = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
memo.put(n, answer);
return answer;
}
public static void main(String[] args) {
System.out.println("fib(40) = " + fibMemo(40, new HashMap<>()));
System.out.println("real computations: " + work); // only 41, plain recursion needs ~330 million calls
}
}Go
package main
import "fmt"
// fibMemo is memoization: recursion + a notebook that remembers answers.
func fibMemo(n int, memo map[int]int, work *int) int {
if v, ok := memo[n]; ok { // peek first: already in the notebook?
return v
}
*work++ // count real computations
if n < 2 {
memo[n] = n // base cases
return n
}
// Compute from smaller questions, then write the answer down.
answer := fibMemo(n-1, memo, work) + fibMemo(n-2, memo, work)
memo[n] = answer
return answer
}
func main() {
work := 0
fmt.Println("fib(40) =", fibMemo(40, map[int]int{}, &work))
fmt.Println("real computations:", work) // only 41, plain recursion needs ~330 million calls
}Time: O(n) · Extra space: O(n). Each distinct question is solved once; the notebook and the recursion depth both grow with n.
Watch out for
- Writing the answer in the notebook but forgetting to peek first, so the cache never saves any work.
- Using a shared notebook for questions whose answers depend on something else (like a different input array). The key must include everything the answer depends on.
- Using
if ($memo[$n])/if (memo[n])as the check: an answer of 0 looks "empty". Check existence instead (isset/has).
Quick check
- What does memoization do?
- Sorts the input
- Remembers answers already worked out so they are never recomputed
- Removes recursion completely
- Where in the function do you check the notebook?
- At the very end
- Only inside the base case
- At the very top, before any work
- Which direction does memoization naturally work?
- Top-down: start from the big question and go down
- Bottom-up: fill from the smallest first
- Sideways