Sub topic 5
Mark-and-Sweep: The Core Algorithm
This chapter assumes you know JavaScript objects, arrays, and functions, and that you have already met two ideas from earlier chapters. The first is reachability: an object survives if a chain of references from a root leads to it. The second is the cycle problem that broke reference counting. Here you will see the algorithm that modern engines build on, how it works step by step, what it costs, and which wrong ideas about it cause trouble in real code.
The Idea in One Sentence
Mark-and-sweep finds every object reachable from the roots and marks it. It then sweeps through the whole heap and frees everything that was not marked.
The collector never asks "how many references point at this object?" It asks "can the program still get here?" That change of question is what makes cycles harmless.
The Two Phases
Phase 1: Mark
The collector starts from the roots, the references the program can always use directly. Roots include:
- global variables and the global object
- local variables and parameters of functions currently on the call stack
- values held by the engine itself, such as pending callbacks and handles kept by the host (DOM, timers, I/O)
From each root, the collector follows every reference to another object, then every reference out of that object, and so on. Each object it reaches gets a mark bit set. An object that is already marked is skipped, so the traversal stops at cycles instead of looping forever.
Phase 2: Sweep
The collector walks the heap linearly. For each object:
- If it is marked, it survives. The mark is cleared so the next cycle starts fresh.
- If it is unmarked, nothing can reach it. Its memory goes back to a free list, a record of free chunks that the allocator can reuse.
A Working Simulation
Real engines do this in C++ over raw memory, but the logic fits in a small JavaScript model. Run this in Node.js or a browser console.
class Heap {
constructor() {
this.objects = new Set(); // every allocated object
this.roots = new Set(); // what the program can reach directly
}
allocate(name) {
const obj = { name, refs: [], marked: false };
this.objects.add(obj);
return obj;
}
mark() {
// An explicit worklist instead of recursion, so deep object
// graphs cannot overflow the call stack.
const worklist = [...this.roots];
while (worklist.length > 0) {
const obj = worklist.pop();
if (obj.marked) continue;
obj.marked = true;
for (const child of obj.refs) {
if (!child.marked) worklist.push(child);
}
}
}
sweep() {
const freed = [];
for (const obj of this.objects) {
if (obj.marked) {
obj.marked = false; // reset for the next collection
} else {
this.objects.delete(obj);
freed.push(obj.name);
}
}
return freed;
}
collect() {
this.mark();
return this.sweep();
}
}
const heap = new Heap();
const a = heap.allocate("A");
const b = heap.allocate("B");
const c = heap.allocate("C");
const d = heap.allocate("D");
heap.allocate("E");
heap.roots.add(a);
a.refs.push(b);
c.refs.push(d);
d.refs.push(c); // a cycle nothing points to
console.log(heap.collect()); // [ 'C', 'D', 'E' ]
heap.roots.delete(a); // like setting the last variable to null
console.log(heap.collect()); // [ 'A', 'B' ]The cycle between C and D gets collected in the first pass. Under reference counting, each of them would keep a count of 1 forever. Mark-and-sweep never looks at counts, so the cycle is just two more unmarked objects.
The makeCycle() example from earlier in the tutorial behaves the same way in a real engine:
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.When makeCycle returns, its stack frame is gone, so the locals a and b stop being roots. The two objects can still reach each other, but no root can reach them.
Tri-Color Marking
Engine source code and GC papers describe marking with three colors. The model makes the worklist explicit, and it is the basis for the incremental collection covered in a later chapter.
| Color | Meaning | In the simulation |
|---|---|---|
| White | Not yet reached. Garbage if still white at the end. | `marked === false`, not in worklist |
| Grey | Reached, but its outgoing references are not yet scanned | in `worklist` |
| Black | Reached, and all its children have been pushed | `marked === true`, popped |
Marking is finished when no grey objects remain. Every object is then black (live) or white (garbage).
The invariant that keeps this correct: a black object never points directly at a white one. If the program could create such a pointer while marking was in progress, the white object could be freed while still in use. Stop-the-world collectors avoid the issue by pausing JavaScript during marking. Incremental collectors need extra machinery, called write barriers, to keep the invariant.
What It Costs
The two phases scale differently, and that difference shapes how engines are designed.
| Phase | Work is proportional to | Implication |
|---|---|---|
| Mark | Number of live objects and references | Lots of long-lived data means long marking |
| Sweep | Total heap size, live plus dead | A big heap takes time to sweep even if most of it is garbage |
In the basic algorithm, JavaScript does not run during either phase. A pause on a heap of several hundred megabytes can be long enough to drop animation frames or add latency to server requests. Most of the advanced GC techniques in V8 and other engines exist to shrink or hide these pauses.
Fragmentation and Compaction
Sweeping frees memory where it lies, which leaves holes between surviving objects. After many cycles the heap can have plenty of free bytes in total while no single gap is large enough for a big allocation. This is called fragmentation.
The fix is compaction: after marking, move live objects together and update every reference to them. The result is called mark-compact.
- Benefit: free memory becomes one contiguous region, and allocation becomes a fast pointer increment.
- Cost: moving objects and rewriting pointers takes more work than sweeping alone.
V8's old generation uses mark-sweep-compact. It marks the whole old space, sweeps most pages, and compacts only the pages that are badly fragmented. Short-lived objects are handled by a different, copying collector, covered in the generational collection chapter.
Gotchas That Follow From the Algorithm
Setting a variable to null does not free anything
obj = null removes one reference. If it was the last path from a root, the object becomes unreachable, and it is freed at some later collection. You cannot know when.
`delete` is not a memory operation
delete obj.prop removes a property, and with it one reference. The same rule applies: memory comes back only if that reference was the last path from a root, and only at the next collection.
Collection timing is not deterministic
Engines start collection based on allocation rates, heap growth, and idle time. Code that depends on garbage being freed at a particular moment is wrong, even if it seems to work in testing.
Reachable but unused is still live
The collector only knows about reachability. It cannot tell that you will never read an entry in a global cache again. If the entry is reachable, it is marked and kept. This gap between reachable and useful is where nearly every real JavaScript memory leak comes from, and the chapters on closures and common leaks deal with it.
Exercises
Exercise
In the Heap simulation, after the first collect(), you run b.refs.push(c2) where c2 is a newly allocated object, and also c2.refs.push(a). Then you call heap.roots.delete(a) and collect again. Which objects are freed, and why does the cycle between a, b, and c2 not keep them alive?
Show answer
A, B, and c2 are all freed. After the root is removed, no root reaches A, so marking never visits A, B, or c2. The cycle A to B to c2 to A doesn't matter, because mark-and-sweep only keeps objects reachable from roots, not objects that reference each other.
Exercise
The mark method uses an explicit worklist array instead of a recursive function. What would go wrong with recursion on a real heap, and which tri-color state do the items in the worklist represent?
Show answer
A long chain of objects, such as a linked list with millions of nodes, would need one stack frame per level and could overflow the call stack. Items waiting in the worklist are grey: reached, but their outgoing references not yet scanned.
Exercise
A service holds 50 MB of live data in a 1.5 GB heap that is mostly garbage. Which phase of plain mark-and-sweep dominates the pause, and what technique addresses the fragmentation that repeated sweeping leaves behind?
Show answer
Sweep dominates, because its cost grows with total heap size while marking only visits the 50 MB of live objects. Compaction (mark-compact) moves live objects together so free memory is contiguous again.