Sub topic 5
Mark-and-Sweep: The Core Algorithm
This chapter assumes you know what reachability and garbage collection roots are, and why reference counting fails on cycles. Both were covered in the previous chapters. Here you will see the algorithm that replaced reference counting in every modern JavaScript engine.
The two phases
Mark-and-sweep does not track how many references point at an object. Each time it runs, it answers one question: can the program still reach this object from a root?
- Mark. The collector starts from the roots: the global object, the variables in the current call stack, and engine-internal handles. It visits every object they reference and sets a "marked" bit on each one. It then follows the references inside those objects, and keeps going until no unvisited objects are left. This is a graph traversal.
- Sweep. The collector walks the heap. Any object without a mark is unreachable, so its memory is reclaimed. The marks are then cleared so the next cycle starts fresh.
Why cycles stop being a problem
Under reference counting, X and Y in the diagram keep each other's count above zero, so they are never freed. Mark-and-sweep never looks at counts. Marking never reaches X or Y, so both are swept together.
function makeCycle() {
const a = {};
const b = {};
a.other = b;
b.other = a;
}
makeCycle();
// a and b still reference each other, but nothing reachable points to them,
// so a mark-and-sweep collector can free both.A toy implementation
The simulation below models the heap as plain objects with a refs array. Real engines work on raw memory, but the logic is the same.
function markAndSweep(roots, heap) {
// Mark phase: iterative depth-first traversal from the roots
const stack = [...roots];
while (stack.length > 0) {
const obj = stack.pop();
if (obj.marked) continue;
obj.marked = true;
stack.push(...obj.refs);
}
// Sweep phase: keep marked objects, drop the rest, reset marks
const survivors = [];
for (const obj of heap) {
if (obj.marked) {
obj.marked = false;
survivors.push(obj);
} else {
console.log(`freed ${obj.name}`);
}
}
return survivors;
}
const make = (name) => ({ name, refs: [], marked: false });
const a = make("A"), b = make("B"), c = make("C");
const x = make("X"), y = make("Y");
a.refs.push(b);
b.refs.push(c);
x.refs.push(y);
y.refs.push(x); // cycle
const heap = markAndSweep([a], [a, b, c, x, y]);
console.log(heap.map((o) => o.name)); // [ 'A', 'B', 'C' ]Running it prints freed X and freed Y, then the survivors.
Costs and trade-offs
| Property | Reference counting | Mark-and-sweep |
|---|---|---|
| Handles cycles | No | Yes |
| When work happens | On every reference change | In batches, when the engine decides |
| Cost driver | Number of pointer writes | Size of the live graph and the heap |
| Pause behaviour | Small, spread-out costs | Can pause the program during a cycle |
The basic algorithm has three weaknesses:
- Stop-the-world pauses. A naive collector halts JavaScript while it marks and sweeps. On a large heap this causes visible jank.
- Fragmentation. Sweeping leaves holes between survivors. Engines such as V8 add a compaction step that moves live objects together. That variant is often called mark-compact.
- Repeated work. Every cycle re-marks long-lived objects that almost never die.
Later chapters cover how V8 deals with these: generational collection for the repeated work, and incremental and concurrent marking for the pauses.
Exercise
In the toy implementation, suppose you add c.refs.push(x) before running the collector. Which objects are freed, and why?
Show answer
None are freed. C is reachable from root A, so marking follows C to X and X to Y. All five objects get marked and survive. The X–Y cycle is now reachable, so it stays alive.
Exercise
Why does the sweep phase reset marked to false on surviving objects?
Show answer
The next collection needs to start with every object unmarked. Otherwise an object that became unreachable after this cycle would still carry an old mark and would wrongly survive.