The Mark Phase
What you'll learn: How the garbage collector identifies which objects are still needed by traversing your program's object graph.
The Core Idea
Once the garbage collector begins its cycle, it enters the mark phase—a systematic sweep through all reachable objects starting from the roots. Think of it like a search-and-rescue team marking every person they can reach from a known safe zone.
The collector begins at the roots (global variables, active function scopes, etc.) and follows every reference it finds. When it encounters an object, it "marks" it as reachable (essentially tagging it as "in use"). Then it follows that object's references to other objects, marking those too. This continues recursively until every object reachable from any root has been marked.
The Traversal Process
Imagine your objects form a web of connections. The mark phase is like walking this web:
- Start at all root objects
- Mark each root as "in use"
- For each marked object, look at every property that references another object
- Mark those referenced objects (if not already marked)
- Repeat step 3-4 until no new objects can be marked
Objects that remain unmarked after this complete traversal have no path back to any root—they're unreachable and can be safely collected.
Why This Matters
The mark phase determines what stays and what goes. Only objects the collector can reach from roots will survive. Everything else is considered garbage, regardless of whether objects reference each other (isolated cycles still get collected).
Key Takeaway: The mark phase walks the entire object graph from roots, tagging every reachable object as "in use"—anything left unmarked is garbage.