Best on a larger screen — the animation and controls have more room to breathe.
Inputs

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:

ObjectnextReachable from A?
ABYes, directly
BCYes, through A
CBYes, through B
DENo
EDNo
FNoneNo
  1. Put A in pending. All six objects start unmarked.
  2. Pop A, mark it, and follow A.next to schedule B.
  3. Pop B, mark it, and schedule C. Then pop C, mark it, and schedule B again.
  4. Pop the repeated B. It is already marked, so skip its reference. pending becomes empty.
  5. With tracing complete, highlight the root-reachable A, B, and C first, then the unreachable D, E, and F. Every slot is still occupied.
  6. Begin sweeping in A through F order. Keep A, B, and C because they are marked.
  7. Reclaim D, then E, then F. The D–E cycle 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 collectorTimeAuxiliary space
Best: no rootsO(V), for the heap scanO(V), including the snapshot of heap keys
AverageO(V)O(V)
Worst: every object reachableO(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 = A with root A marks A once 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 F keeps F even though F.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 B and C.
  • Removing the already-marked guard makes the default traversal repeat B -> C -> B forever.
  • Treating any incoming reference as proof of liveness would incorrectly keep D and E.
  • 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.