liveBook · Manning

Garbage collection

As explained in JavaScript in Depth

A garbage collector is a runtime component that automatically identifies and reclaims memory occupied by unreachable objects.

A server can handle requests smoothly, then pause in the middle of an HTTP response even though its timers and microtasks usually run on time. The garbage collector may be reorganizing memory. Every allocation adds potential collection work, but the cost depends heavily on which objects remain reachable when collection runs. section 9.0 section 9.4.2

JavaScript does not specify a collection strategy. V8 uses a generational collector, while JavaScriptCore uses a different, non-moving collector. In V8, objects that survive young-generation collections may be promoted to the old generation, where they add to later collection work. A collector can reclaim an object only after no reachable path keeps it alive; it does not run on a schedule your code controls. section 9.0 section 11.2.5 section 9.4.2

function scheduleSendNotification(userId) {
  setTimeout(() => {
    sendNotification(userId)
  }, 5000);
}
function processRequest(rawBody) {
  const userId = JSON.parse(rawBody).userId;
  scheduleSendNotification(userId);
}

Pass only the parsed user ID into the timer’s closure. The larger request body then has no path through that closure keeping it reachable; setting the original variable to null afterward is not the underlying fix. section 9.1.1

To reduce collection work, distinguish allocation from retention:

  • Let short-lived objects become unreachable promptly. A high object count alone need not cause heavy collection when those objects die young. section 9.4.2
  • Avoid holding per-request objects across timers, listeners, or awaits when a smaller value will do. Unnecessary survival can promote objects into the old generation. section 9.4.2 section 11.2.5
  • In a stream, accumulate a count, checksum, or hash rather than retaining processed chunks when the aggregate is all you need. section 10.7.2
const allChunks = [];
 
const transform = new TransformStream({
  transform(chunk, controller) {
    allChunks.push(chunk);  // #A
    controller.enqueue(processChunk(chunk));
  }
});

The transform forwards each processed chunk but also saves the original in allChunks. That retained reference defeats the stream’s small-working-set advantage and makes the collector trace the accumulated chunks. section 10.7.2

Measure before changing code. A healthy heap-used graph rises and falls with level post-collection troughs; troughs that keep rising suggest a leak. Frequent young-generation collections can instead indicate high allocation volume, while old-generation collections under load can point to objects surviving too long. Use allocation sampling, snapshot comparisons, and --trace-gc to investigate those different causes. section 11.1.1 section 11.2.5

How JavaScript in Depth covers it

How deep it goes
Traces reachability and V8 promotion into old-generation collection work, while noting that ECMAScript leaves collector design unspecified.
Examples
Uses a timer retaining a request body, a stream retaining chunks, and heap-usage patterns.
What it assumes
Assumes familiarity with JavaScript objects, closures, and asynchronous code while developing the collection cost model from everyday allocations.
What you can do after
Diagnose/debug collection pressure with --trace-gc and heap measurements, then shorten unnecessary reachability paths.
How it connects
Links garbage collection to closures, promises, streams, the event loop, and memory leaks.

Also explained in

Compare how 12 books explain garbage collection →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of JavaScript in Depth. The section links point to the parts of the book it draws on.