How does mark-and-sweep garbage collection actually determine which objects are reachable?
Short answer
The collector starts from a set of 'roots' (global objects, currently executing call stack, active closures) and traverses every reference reachable from them, marking each visited object as live; anything left unmarked after this traversal is unreachable garbage and gets swept…
Advertisement
AModel answer
The collector starts from a set of 'roots' (global objects, currently executing call stack, active closures) and traverses every reference reachable from them, marking each visited object as live; anything left unmarked after this traversal is unreachable garbage and gets swept (freed).
// Roots -> traversal example (conceptual)
// window -> app -> currentUser -> profile (all marked reachable)
// an object with zero incoming references from any root is sweptReal-world example
Explaining why two objects that only reference EACH OTHER, but nothing else references them, are still correctly collected (unlike naive reference counting).
Likely follow-ups
- Why does mark-and-sweep handle circular references correctly, unlike simple reference counting?
Related topics