Memoization

On this page 7

Memoization is an optimization technique that stores the result of a function call in a lookup table keyed by its arguments, so that a later call with the same arguments returns the stored value instead of repeating the computation. In the study of algorithms within programming, it is the standard way to turn an exponential recursive solution into a polynomial one whenever the recursion keeps solving the same overlapping subproblems.

The idea trades memory for time: each distinct input is computed once, and every repeat costs only a lookup. The term was coined by Donald Michie in 1968 from the Latin word memorandum, and it is deliberately spelled without an r to distinguish it from ordinary memorization.

How memoization intercepts repeated calls

A memoized function checks a cache before doing any work. When the arguments form a key that is already present, the stored result is returned immediately; when the key is missing, the function computes the result, writes it to the cache and then returns it. The caller cannot tell the difference except through speed.

The classic illustration is the naive recursive Fibonacci function. Computing fib(40) without a cache triggers more than 300 million recursive calls, because fib(38), fib(37) and smaller values are recomputed again and again. With memoization, each of the 41 distinct inputs is evaluated exactly once, and the running time drops from roughly O(φ^n) to O(n).

The table below traces the components every memoized function needs, regardless of the language or library used to implement it.

ComponentRoleTypical implementation
Cache keyIdentifies a distinct inputTuple of arguments, string, or hash
Cache storeHolds computed resultsHash map, array, or dictionary
Lookup stepReturns a hit without recomputationConstant-time map access
Compute stepRuns the original logic on a missThe unmodified function body
Eviction policyLimits memory growthLRU, size cap, or none
Components of a memoized function

Conditions that make memoization correct

Memoization is safe only when the function is referentially transparent: the same arguments must always produce the same result, and the function must have no observable side effects. A function that reads the clock, a database, a random generator or mutable global state will return stale or wrong values once it is cached.

The second requirement is a well-defined key. Arguments must be hashable or reducible to a stable identifier. Mutable objects such as lists or dictionaries are dangerous keys, because a caller may modify the object after the call, and the cache then maps an outdated value to a key that no longer describes the input. Floating-point arguments raise a related problem, since values that are mathematically equal may differ in their last bits and miss the cache.

  • Pure functions: deterministic output and no side effects.
  • Immutable or hashable arguments: stable keys for every call.
  • Overlapping inputs: the same arguments actually recur during execution.
  • Bounded input space: the number of distinct keys fits in available memory.

Memoization is closely tied to dynamic programming, and the two are often described as top-down and bottom-up versions of the same strategy. Memoization keeps the natural recursive structure and fills the table lazily, only for subproblems that are actually reached. Bottom-up tabulation fills the table iteratively in a fixed order, which avoids recursion overhead but may compute entries that are never needed.

The comparison below separates memoization from the neighboring approaches with which it is most often confused.

ApproachOrder of evaluationMain strengthMain weakness
MemoizationTop-down, on demandComputes only reachable subproblemsRecursion depth and call overhead
Bottom-up tabulationIterative, fixed orderNo stack limits, easy space reductionMay fill unused table entries
General cachingAny order, often externalWorks across processes and requestsNeeds invalidation for changing data
Divide and conquerTop-down, no reuseSimple for independent subproblemsWastes work when subproblems overlap
Memoization versus related approaches

The distinction from general caching matters in practice. A web cache stores responses whose underlying data can change, so it relies on expiry times and invalidation. A memoization table assumes the result never becomes invalid, which is exactly why purity is a precondition.

Typical applications and their complexity gains

Memoization delivers its largest gains on recursive problems with overlapping subproblems, where the number of distinct states is far smaller than the number of recursive calls. The table lists common cases and the effect of caching on their running time.

ProblemDistinct statesWithout memoizationWith memoization
Fibonacci numbersnExponentialO(n)
Longest common subsequencem × nExponentialO(m × n)
0/1 knapsackn × capacityO(2^n)O(n × capacity)
Edit distancem × nExponentialO(m × n)
Counting grid pathsrows × columnsExponentialO(rows × columns)
Effect of memoization on common problems

Beyond textbook algorithms, memoization appears in parsers (packrat parsing guarantees linear time for parsing expression grammars), in compilers that cache type inference results, and in user interface frameworks that skip re-rendering a component when its inputs are unchanged. Many languages provide ready-made tools, such as functools.lru_cache and functools.cache in Python or memo helpers in JavaScript frameworks.

Costs, pitfalls and common mistakes

The main cost of memoization is memory proportional to the number of distinct keys. An unbounded cache in a long-running service can grow until it exhausts the heap, which is why production code usually caps the size and evicts entries with a least recently used (LRU) policy. Recursion depth is a second limit: a top-down solution for n = 100,000 may overflow the call stack where an iterative version would not.

The table summarizes frequent mistakes, how they show up and how experienced developers correct them.

MistakeSymptomFix
Caching an impure functionStale or inconsistent resultsMemoize only deterministic code
Mutable arguments as keysWrong hits or hashing errorsConvert to immutable tuples or IDs
Unbounded cache sizeSteady memory growthSet a size limit with LRU eviction
Deep recursionStack overflow on large inputsSwitch to bottom-up tabulation
Shared cache across threadsRace conditions or duplicate workUse locking or per-thread caches
Memoization mistakes and fixes

A final pitfall is memoizing cheap functions. When the computation costs less than hashing the arguments and probing the table, the cache makes the program slower. Memoization pays off only when the hit rate is high and each miss is expensive.

A plain-language summary

Memoization means a program remembers answers it has already worked out. Imagine a student who solves a long math problem and writes the answer in a notebook. The next time the same problem appears, the student simply looks it up instead of solving it again.

This makes programs much faster when they keep asking the same questions. The price is the notebook itself: it takes up space, and it only works if the answer to a question never changes over time.

An example from practice

A logistics developer writes a route-pricing function that finds the cheapest way to split a shipment of 500 kilograms across trucks of several capacities. The first recursive version explores every combination and takes more than a minute for a single quote, because it recalculates the best price for the same remaining weight thousands of times.

The developer adds memoization keyed on the remaining weight and the set of available truck types. The number of distinct states falls to a few thousand, each computed once, and a quote now returns in under 50 milliseconds. Because the price table changes daily, the cache is cleared whenever new rates are loaded, which keeps the function pure for the lifetime of each cache and prevents stale quotes.