← Back to JavaScript, page 5

javascript-0088 · Hard senior

How does garbage collection work in JavaScript engines, and why is reference counting not used?

Engines free memory with tracing garbage collection: starting from roots such as globals and the active stack, they mark every reachable object and reclaim the rest. This handles reference cycles, which simple reference counting cannot. Modern engines are generational, run parts concurrently and incrementally, and collect young short-lived objects far more often than old ones.

Full answer

JavaScript has no explicit free. The engine decides when memory can be reclaimed. The rule is reachability: an object stays alive while some chain of references leads to it from a root. Roots are global variables, the local variables and arguments of functions currently on the call stack, and internal engine references.

The basic algorithm is mark-and-sweep. The collector marks every object reachable from the roots by walking references, then sweeps (frees) every unmarked object. Because it traces from the roots, two objects that only point to each other are collected once nothing else reaches them. Reference counting, which frees an object when its count falls to zero, fails here: the cycle keeps both counts at one forever. Old browsers that mixed counted DOM objects with script objects leaked memory this way, and modern engines do not use counting for JavaScript objects.

Real collectors are more complex, since a full mark-and-sweep pause would freeze the page. V8 uses a generational design based on the observation that most objects die young. New objects go into a small young generation that is collected often and quickly by copying survivors. Objects that survive a couple of rounds move to the old generation, which is collected less often with a mark-sweep-compact approach. Marking is done incrementally and concurrently on helper threads, with short pauses on the main thread, and compaction reduces fragmentation.

Practical consequences: allocation is cheap, but high allocation rates cause frequent young collections, so avoid creating large amounts of short-lived garbage in hot loops. The timing is not controllable, so code cannot depend on it, which is why WeakRef and finalization callbacks are unreliable for core logic. Leaks are objects that stay reachable, which is why listeners, timers, and caches are the usual suspects.

javascript
class Heap {
  constructor() {
    this.objects = new Map();
    this.roots = new Set();
  }
  allocate(name, ...refs) {
    this.objects.set(name, { name, refs: new Set(refs) });
    return name;
  }
  link(from, to) {
    this.objects.get(from).refs.add(to);
  }
  unlink(from, to) {
    this.objects.get(from).refs.delete(to);
  }
  markAndSweep() {
    const marked = new Set();
    const stack = [...this.roots];
    while (stack.length) {
      const name = stack.pop();
      if (marked.has(name) || !this.objects.has(name)) continue;
      marked.add(name);
      for (const ref of this.objects.get(name).refs) stack.push(ref);
    }
    const freed = [];
    for (const name of [...this.objects.keys()]) {
      if (!marked.has(name)) {
        this.objects.delete(name);
        freed.push(name);
      }
    }
    return freed;
  }
  referenceCounts() {
    const counts = new Map([...this.objects.keys()].map((name) => [name, 0]));
    for (const { refs } of this.objects.values()) for (const ref of refs) counts.set(ref, (counts.get(ref) ?? 0) + 1);
    for (const root of this.roots) counts.set(root, (counts.get(root) ?? 0) + 1);
    return Object.fromEntries(counts);
  }
}

const heap = new Heap();
heap.allocate('app');
heap.roots.add('app');
heap.allocate('cache');
heap.link('app', 'cache');
heap.allocate('user');
heap.allocate('session');
heap.link('user', 'session'); // a cycle: user and session point to each other
heap.link('session', 'user');
heap.link('app', 'user');

console.log('before:', [...heap.objects.keys()]);
console.log('collected while app still references user:', heap.markAndSweep());

heap.unlink('app', 'user');
console.log('reference counts after unlinking:', heap.referenceCounts());
console.log('counting would keep the cycle alive; mark-and-sweep frees:', heap.markAndSweep());

heap.allocate('listener');
heap.link('app', 'listener'); // forgotten reference: still reachable, so never freed
heap.allocate('bigBuffer');
heap.link('listener', 'bigBuffer');
console.log('leak candidate survives:', heap.markAndSweep(), [...heap.objects.keys()]);
heap.unlink('app', 'listener');
console.log('after removing the reference:', heap.markAndSweep());

Run with Node.js v24.22.1 as js-88.js; two runs gave identical output. Output: before: [ 'app', 'cache', 'user', 'session' ] collected while app still references user: [] reference counts after unlinking: { app: 1, cache: 1, user: 1, session: 1 } counting would keep the cycle alive; mark-and-sweep frees: [ 'user', 'session' ] leak candidate survives: [] [ 'app', 'cache', 'listener', 'bigBuffer' ] after removing the reference: [ 'listener', 'bigBuffer' ]

Key points

  • Reachability from roots decides what lives; unreachable objects are reclaimed.
  • Mark-and-sweep handles cycles; reference counting does not.
  • Engines are generational: young objects are collected often, old ones rarely.
  • Marking is incremental and concurrent to keep pauses short.
  • Timing is not controllable; leaks are objects that remain reachable.

Common mistakes

  • Believing JavaScript uses reference counting.
  • Saying that setting a variable to null frees memory immediately; it only makes the object unreachable.
  • Depending on the timing of garbage collection or finalizers.
  • Calling an unreachable cycle a leak; cycles are collected, while reachable-but-unused objects are the leaks.

Follow-ups

  • Why do generational collectors perform well for most programs?
  • What is a write barrier, and why do incremental collectors need one?
  • How do you trigger and observe garbage collection while debugging in Node.js?

Tips

  • Define reachability first, then walk through mark and sweep.
  • Explain the cycle case; it is the reason counting is not used.
  • Mention generations in one sentence and say that timing cannot be relied on.