Garbage Collection
Garbage collection reclaims heap storage that a program can no longer reach. A mark-sweep collector starts from runtime roots, follows references, and marks the objects it discovers. Only after that traversal finishes does it reclaim unmarked objects. An unreachable cycle can therefore be collected even though its members still reference one another.
Two objects pointing at each other do not prove that your program can use either one. They may simply be keeping each other company in a part of the heap nobody can reach. The useful question is whether a path starts at a root and ends at the object.
How Garbage Collection Finds Live Objects
A root is a starting reference known to the runtime, such as a reference in an active stack frame or a global variable. An object is reachable if a root points to it directly, or if a chain of references from a root reaches it. Follow arrows in their direction: an unreachable object pointing to a live object does not make the source live.
A global cache can keep a large object reachable after the program no longer needs it. Until that cache entry is removed, tracing still finds the object and preserves it. Reachable means the program can access it, not that it intends to use it again.
This collector pauses the program so its references cannot change during the collection.
It starts with an empty marked set and a pending stack containing the roots. Each pop
chooses an object to inspect. If it is already marked, skip it. Otherwise mark it, read its
next field, and schedule that target if the field is not None.
The distinction between scheduling and marking matters. An object can appear in pending
more than once. It is marked when it is first inspected; a later inspection takes the skip
branch. That guard lets the collector finish even when the reachable graph contains a cycle.
While pending still contains work, an unmarked object might simply be waiting to be found.
Once the stack is empty, every object reachable from the roots has been marked. Now sweep
all allocated objects: keep the marked ones in place, and reclaim the unmarked ones. Sweep
does not follow their references.
Garbage Collection Step by Step
The default heap has six objects, one root pointing to A, and these fields:
| Object | next | Reachable from A? |
|---|---|---|
| A | B | Yes, directly |
| B | C | Yes, through A |
| C | B | Yes, through B |
| D | E | No |
| E | D | No |
| F | None | No |
- Put
Ainpending. All six objects start unmarked. - Pop
A, mark it, and followA.nextto scheduleB. - Pop
B, mark it, and scheduleC. Then popC, mark it, and scheduleBagain. - Pop the repeated
B. It is already marked, so skip its reference.pendingbecomes empty. - With tracing complete, highlight the root-reachable
A,B, andCfirst, then the unreachableD,E, andF. Every slot is still occupied. - Begin sweeping in
AthroughForder. KeepA,B, andCbecause they are marked. - Reclaim
D, thenE, thenF. TheD–Ecycle has no path from a root, so its internal references do not protect it. Three slots remain occupied and three become reusable.
Watch the mark badges change from 0 to 1, then watch the sweep cursor change unmarked
objects into Free slots. The reachable objects never move. Before trying another run, predict:
If only root D is added, how many slots will be reclaimed? Click Add root D in Inputs,
then Play. This loads Root the second cycle: the references stay unchanged, D and E
now survive, and only F is reclaimed.
Time and Space Complexity
Let V be the number of allocated objects and E their reference fields. Marking visits the
reachable part; sweeping still examines all allocated objects. General mark-sweep has
O(V + E) worst-case time complexity. This lesson gives each object at most one reference,
so E <= V.
| This one-field collector | Time | Auxiliary space |
|---|---|---|
| Best: no roots | O(V), for the heap scan | O(V), including the snapshot of heap keys |
| Average | O(V) | O(V) |
| Worst: every object reachable | O(V) | O(V) |
marked, pending, and the key snapshot use linear space. The Python listing is the small
collector being explained, not Python's own garbage collector. del heap[obj] represents
releasing a slot in this model; deleting a Python dictionary entry is not a general command
to return memory to the operating system.
Edge Cases
- No roots: all six objects are reclaimed, including cycles.
- Self-loop:
A.next = Awith rootAmarksAonce and skips its repeated visit. - Shared tail: two roots may lead to the same object. The second visit skips an existing mark.
- Rooted leaf: root
FkeepsFeven thoughF.next = None; outgoing references are not required for an object to be live. - Everything retained: roots
[A, D, F]keep all six default objects. A forgotten root can retain unwanted data. Reachability cannot tell whether the program intends to use it again.
Common Mistakes
- Sweeping after marking only the roots would reclaim indirectly reachable
BandC. - Removing the already-marked guard makes the default traversal repeat
B -> C -> Bforever. - Treating any incoming reference as proof of liveness would incorrectly keep
DandE. - Following references during sweep confuses its heap scan with the earlier marking traversal.
- Moving survivors together depicts compaction, which this mark-sweep collector does not do.
A Note on Simplification
The animation uses six equal-size objects with one optional strong reference each. Real objects can have many reference fields. Roots are supplied explicitly; root discovery, allocator metadata, weak references, finalizers, and variable-size allocations are omitted. Each run uses a fresh mark set and pauses the program throughout marking and sweeping.
Generational, incremental, concurrent, copying, and compacting collectors add machinery beyond this model. Reference counting is another approach; this lesson does not implement it. A freed slot means reusable space inside the heap, without a promise that process memory usage drops.
For the runtime connection, see V8's explanation of marking and roots. Its discussion of concurrent mutation also explains why allowing a program to change references during this simple traversal would require additional safeguards.
Keep exploring
A few lessons that share the same technique or lead into the next idea.
Premium players need paid access. Every Explain doc is free.
Found a mistake or something unclear? Leave feedback.