Sub topic 12
The Hidden Memory Cost of Top-Down Memoization
This chapter assumes you can write a memoized recursive function, read Big-O space bounds, and know the 0/1 knapsack and LCS recurrences. Earlier chapters cut memory by discarding table rows the recurrence no longer reads. Top-down memoization cannot do that. The sections below show where its memory goes, how to estimate it before you run out, and what to change when it is too large.
Why Memoization Keeps Everything
A bottom-up loop visits states in a fixed order. Because of that, you know when a row will never be read again and can overwrite it. A memoized recursion visits states in whatever order the call tree produces. Its cache has no idea which entries a future call will look up, so it keeps every entry until the top-level call returns.
The total memory of a memoized solution has two parts:
- Cache memory. Distinct states visited, multiplied by the bytes stored per entry.
- Stack memory. Maximum recursion depth, multiplied by the size of one stack frame.
Rolling rows, single arrays, and modulo buffers shrink neither part. They only work when you control the visiting order.
Cost per Entry: Dictionaries Are Not Arrays
The asymptotic bound is the same for both styles. A 0/1 knapsack with n items and capacity C has O(n·C) states either way. The constant factor is very different, though.
A Python list slot holds an 8-byte pointer. Small integers from -5 to 256 are shared objects, and larger ones cost about 28 bytes each. A functools.lru_cache entry stores more:
- a key object built from the arguments, typically a tuple of about 56 bytes plus its integer elements,
- a hash-table slot in the underlying dictionary, with spare capacity for resizing,
- the result object.
In practice that comes to about 100–200 bytes per state on CPython. A flat bottom-up array needs about 8 bytes per state. Exact figures vary by Python version and platform, so measure instead of trusting a constant.
| Aspect | Top-down with `lru_cache` | Bottom-up full table | Bottom-up compressed |
|---|---|---|---|
| States stored | Only states visited | All states | One or two rows |
| Bytes per state | About 100–200 | About 8 (pointer) | About 8 |
| Can discard old states | No | No | Yes |
| Extra stack | O(depth) frames | None | None |
| Recursion-limit risk | Yes | No | No |
Measuring It
The script below solves the same knapsack instance two ways and records peak memory with tracemalloc. The single-array version uses the downward loop from the earlier chapter on loop direction.
import random
import sys
import tracemalloc
from functools import lru_cache
def knapsack_memo(weights, values, capacity):
n = len(weights)
@lru_cache(maxsize=None)
def best(i, c):
if i == n:
return 0
skip = best(i + 1, c)
if weights[i] <= c:
return max(skip, best(i + 1, c - weights[i]) + values[i])
return skip
result = best(0, capacity)
entries = best.cache_info().currsize
best.cache_clear()
return result, entries
def knapsack_array(weights, values, capacity):
dp = [0] * (capacity + 1)
for w, v in zip(weights, values):
for c in range(capacity, w - 1, -1):
dp[c] = max(dp[c], dp[c - w] + v)
return dp[capacity]
def peak_bytes(fn, *args):
tracemalloc.start()
out = fn(*args)
_, peak = tracemalloc.get_traced_memory()
tracemalloc.stop()
return out, peak
if __name__ == "__main__":
random.seed(1)
n, capacity = 100, 2000
weights = [random.randint(1, 60) for _ in range(n)]
values = [random.randint(1, 500) for _ in range(n)]
(memo_result, entries), memo_peak = peak_bytes(
knapsack_memo, weights, values, capacity
)
array_result, array_peak = peak_bytes(
knapsack_array, weights, values, capacity
)
assert memo_result == array_result
print(f"answer: {memo_result}")
print(f"cache entries: {entries}")
print(f"memo peak: {memo_peak / 1e6:.2f} MB")
print(f"array peak: {array_peak / 1e3:.2f} KB")
print(f"bytes per entry: {memo_peak / entries:.0f}")
print(f"recursion limit: {sys.getrecursionlimit()}")On a typical CPython 3.11 or later build, the memoized version peaks at tens of megabytes while the array version stays at tens of kilobytes. The answers are identical. The printed bytes-per-entry figure is the constant you should plug into estimates for your own environment.
cache_info().currsize counts the states that were actually visited. It can be well below n·(C+1) when many capacities are unreachable. That is memoization's real advantage. The chapter on storing only reachable states covers when it pays off.
The Stack Is Memory Too
Every pending call holds a frame. In knapsack_memo the depth reaches n + 1, because each call advances i by one. With n = 100 that is fine. With n = 5000 it raises RecursionError, because CPython's default limit is 1000.
Common depth patterns:
| Recurrence | Maximum depth |
|---|---|
| Fibonacci `f(n-1) + f(n-2)` | n |
| Knapsack over items `best(i+1, ...)` | n |
| LCS `L(i-1, j)`, `L(i, j-1)` | m + n |
| Interval DP `f(l, r)` splitting at k | about r - l |
sys.setrecursionlimit raises the Python-level counter, but it does not enlarge the C stack underneath. Set the limit high enough and the interpreter can crash with a segmentation fault instead of raising a clean exception. If you must go deep, run the work in a thread with a larger stack set by threading.stack_size. Converting to an iterative form is usually the better fix.
Estimating Before You Run
Do the arithmetic before writing the solution:
- Count the distinct states the recursion can reach. Use the full state space as an upper bound.
- Multiply by the bytes per entry, about 150 for
lru_cacheon CPython or your measured figure. - Find the longest chain of nested calls and compare it with the recursion limit.
For example, a memoized edit distance on two 4000-character strings has up to 4001 × 4001 ≈ 16 million states. At 150 bytes each that is about 2.4 GB, and the depth reaches about 8000. Both numbers rule the approach out. The bottom-up single-row version needs about 4001 slots.
Ways to Limit Memoization Memory
When the estimate is too large, pick the first remedy that applies:
- Switch to bottom-up when the reachable states are dense. If most of the table gets visited anyway, memoization's only remaining benefit is convenience. Tabulation lets you apply the row and variable reductions from earlier chapters.
- Replace the dictionary with a preallocated array. Index a list or
array.arrayby state instead of hashing tuples. You keep the top-down structure and get about 8 bytes per state. Use a sentinel such as-1for "not computed". - Shrink the key. Encode
(i, c)as the single integeri * (C + 1) + c. This removes the tuple allocation per entry. - Drop derivable arguments. If one argument can be computed from the others, remove it from the signature so it no longer multiplies the key space.
- Remove recursion depth with an explicit stack. An iterative DFS that pushes pending states onto a Python list keeps the cache but avoids C-stack limits.
- Clear caches between independent inputs, as shown above.
Here is the array-backed version of the knapsack memo. It is still top-down, but each entry is a slot in a flat list.
def knapsack_memo_array(weights, values, capacity):
n = len(weights)
width = capacity + 1
memo = [-1] * ((n + 1) * width)
def best(i, c):
key = i * width + c
if memo[key] != -1:
return memo[key]
if i == n:
result = 0
else:
result = best(i + 1, c)
if weights[i] <= c:
result = max(result, best(i + 1, c - weights[i]) + values[i])
memo[key] = result
return result
return best(0, capacity)
print(knapsack_memo_array([1, 3, 4, 5], [1, 4, 5, 7], 7)) # 9The trade-off is that it preallocates the full state space even if few states are reached. A dictionary wins when visited states are sparse, and the flat array wins when they are dense.
Exercise
You plan to compute LCS of two 3000-character strings with a memoized function L(i, j) decorated by lru_cache(maxsize=None). Estimate its cache memory and recursion depth, say whether it will run with default CPython settings, and name a replacement with its memory cost.
Show answer
There are up to 3001 × 3001 ≈ 9 million states. At about 150 bytes per entry that is roughly 1.35 GB. The depth can reach about m + n = 6000, which exceeds the default recursion limit of 1000, so it raises RecursionError before memory even becomes the problem. A bottom-up two-row LCS sized to the shorter string uses 2 × 3001 slots, about 48 KB of pointers, and no recursion.
Exercise
A teammate changes @lrucache(maxsize=None) to @lrucache(maxsize=1024) on a memoized edit-distance function to save memory. The tests still pass on short strings, but long inputs never finish. Explain why.
Show answer
With a bounded cache, least-recently-used states are evicted and recomputed when they are needed again. Edit distance has heavily overlapping subproblems, so evicted states keep being recomputed along with their own evicted dependencies, and the running time grows toward the exponential cost of plain recursion. Short inputs fit in 1024 entries, which hides the problem. To save memory, use a single-row bottom-up table instead of bounding the cache.
Exercise
For the knapsack instance in the measurement script, when would the dictionary-based lrucache use less memory than knapsackmemo_array?
Show answer
When the number of visited states, cache_info().currsize, multiplied by bytes per dictionary entry is less than (n + 1) × (capacity + 1) × 8 bytes. That happens when reachable capacities are very sparse, for example when all weights are large multiples of a common value, so only a small fraction of the (i, c) pairs is ever visited.