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 follow the dependency analysis from earlier chapters. Top-down memoization looks cheap because you never declare a table. The memory is still used, and it comes from two places you don't see in the code.
Two Hidden Costs
A memoized solution uses memory in two ways:
- The cache. Every distinct state the recursion visits stays stored until the cache is cleared. You cannot drop old rows, because you don't control the order in which states are visited.
- The call stack. Each pending recursive call holds a stack frame. The deepest chain of calls sets the peak stack use, and that depth often grows with the input size.
Seeing It in Python
from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
print(fib(500))
print(fib.cache_info().currsize) # 501 cached entries remain after the call
fib.cache_clear()
try:
fib(5000)
except RecursionError:
print("recursion too deep")The rolling-variable version of Fibonacci uses O(1) space. The memoized version uses O(n) for the cache and O(n) for the stack. With Python's default recursion limit of about 1000, fib(5000) fails before it computes anything.
Per-Entry Overhead
Big-O hides constant factors, and in a dictionary-based cache those factors are large. In CPython, each cached entry stores a hash-table slot, a key object (often a tuple), and a value object. That can come to 100 bytes or more per entry. A list of small integers costs about 8 bytes per slot for the pointer, and the integers themselves are shared. A memoized 2D DP with millions of states can therefore use ten times the memory of the equivalent bottom-up table.
| Approach | Cache space | Stack space | Can apply rolling rows? |
|---|---|---|---|
| Memoized recursion (dict) | Visited states × large constant | Max recursion depth | No |
| Bottom-up full table | All states × small constant | O(1) | Yes |
| Bottom-up with rolling rows | One or two rows | O(1) | Already applied |
When Memoization Still Wins
Top-down recursion only visits states that the starting state can reach. If most of the table is unreachable, as in a knapsack with a few large weights, the cache can be much smaller than the full table. This is the sparse-state idea from the previous chapter, which you get without extra work.
Limiting the Cost
- Estimate both numbers before you run: the count of distinct states and the maximum recursion depth.
- If the depth can exceed about 1000, convert to bottom-up. Raising
sys.setrecursionlimitcan crash the interpreter when the C stack runs out. - If the states form a dense grid, replace the dict with a preallocated list, or move to bottom-up so you can use rolling rows.
- Call
cache_clear()between independent inputs so that old entries don't pile up.
Exercise
You memoize LCS on two strings of length 2000 each, with lcs(i, j) recursing to (i-1, j-1), (i-1, j), or (i, j-1). Give the worst-case cache size and recursion depth, and say whether it runs in default Python.
Show answer
The cache can hold up to 2001 × 2001 ≈ 4 million entries, which is hundreds of megabytes in a dict. The deepest call chain decrements i or j one at a time, so it can reach about 4000 frames. That exceeds the default limit of about 1000, so it raises RecursionError. A bottom-up version with two rows uses O(2000) space and no recursion.
Exercise
Why can't you apply the two-row trick to a memoized LCS without changing the code structure?
Show answer
Rolling rows works only when you know that row i-1 is no longer needed once row i is finished. Recursion visits states in whatever order the calls happen, so the cache cannot safely discard any row. You must switch to a bottom-up order first.