Sub topic 11
Memory retention and garbage collection
This chapter assumes you know how path copying and structural sharing work, and that you know what a reference is in Python or JavaScript. It covers one consequence of sharing: a node stays in memory as long as any version still reaches it.
Reachability decides what lives
Garbage collected runtimes free an object when no live reference can reach it. They don't track which version "owns" a node. With structural sharing, a node can belong to many versions at once, so it is freed only after every version that reaches it has become unreachable.
If you drop Version A, node A1 becomes garbage. Node S stays, because Version B reaches it. If you then drop Version B, S goes too, except that B1 stays while Version C reaches it.
Watching it happen
This example uses a weak reference. A weak reference observes an object without keeping it alive.
import gc
import weakref
from dataclasses import dataclass
from typing import Optional
@dataclass(frozen=True)
class Node:
head: int
tail: Optional["Node"] = None
shared = Node(2, Node(3))
old = Node(1, shared)
new = Node(0, shared)
probe = weakref.ref(shared)
del shared, old
gc.collect()
assert probe() is not None # `new` still reaches the shared tail
del new
gc.collect()
assert probe() is None # no version reaches it now
print("shared tail was freed only after the last version was dropped")Common ways memory is retained
- Unbounded history. An undo stack that stores every version never lets old nodes go. Sharing keeps each entry small, but the total still grows with every edit.
- A small handle on a large version. One reference to an old root keeps every node reachable from it. A cache that holds a single old state can keep a large tree alive.
- Closures and listeners. A callback that captured an old version keeps it alive until the callback is removed.
- Replaced values that stay referenced. The version you replaced is not freed if a log, a debug tool, or a memoization table still holds it.
Bound the history to fix the first problem:
from collections import deque
history = deque(maxlen=100) # the oldest version is dropped automatically
history.append({"count": 0})
history.append({"count": 1})
assert len(history) == 2When the deque is full, the dropped version loses one reference. Its private nodes become garbage. Nodes shared with newer versions stay.
What the collector costs you
Persistent updates allocate many small, short-lived nodes: a path of roughly log n nodes per update. Generational collectors handle this well, because most of these nodes die young and are cheap to reclaim. Pressure shows up in two places:
- Allocation rate. A tight loop that does one persistent update per item creates a lot of garbage. Transients (covered in the previous chapter) reduce it.
- Long-lived old versions. A version that survives several collections gets promoted to older generations. Dropping it later can need a more expensive collection.
In a reference-counting runtime such as CPython, freeing a deep structure can cascade. Dropping the last reference to a very long list frees one node, which frees the next, and so on. CPython guards against stack overflow here, but the pause is still proportional to the number of nodes freed.
Practical checks
- Decide how many versions you must keep, and cap the history to that number.
- Keep references to old roots short-lived. Don't store them in long-lived caches.
- Measure with a memory profiler before tuning. Sharing often makes the real footprint much smaller than the sum of the version sizes.
Exercise
A text editor stores every edit as a new persistent version in a list, and never removes entries. Each edit changes about 20 nodes out of 100,000. After 10,000 edits, why does memory keep growing, and what is one fix?
Show answer
Each version keeps its roughly 20 changed nodes reachable through the list, and every old version still reaches the nodes it replaced. About 200,000 changed nodes accumulate, plus the shared base. Sharing stops each entry from being a full copy, but it can't free nodes that a stored version still references. Fix it by capping the history, for example with a deque of fixed maximum length, so the oldest versions become unreachable and are collected.