Sub topic 3
Finding Leaks with Heap Snapshots and Allocation Profiling
This chapter assumes you know reachability, mark-and-sweep, and the common leak patterns from the earlier chapters, and that you can run Node.js or open Chrome DevTools.
Heap Snapshots and Allocation Timelines
A heap snapshot records every live object and the references that keep it alive. To find a leak, use three snapshots:
- Take a snapshot to get a baseline.
- Repeat the suspect action several times, such as opening and closing a dialog.
- Take a second snapshot, repeat the action again, and take a third.
Then use the Comparison view. Objects whose count keeps rising are your suspects. Open the Retainers panel to see which chain of references connects a suspect to a root. In the Summary view, searching for "Detached" finds DOM nodes that were removed from the page but are still referenced from JavaScript. The allocation timeline shows when objects were allocated. Blue bars that stay after a collection mark memory that was never freed.
Generational and Concurrent Collection in V8
Most objects die young. V8 therefore allocates new objects in a small young generation and cleans it often with a fast scavenger. Objects that survive two scavenges are promoted to the old generation, which is collected less often with mark-and-sweep. To keep pauses short, V8 also marks incrementally (in small steps between JavaScript work), runs some work in parallel on helper threads, and does some marking and sweeping concurrently while your code keeps running.
WeakRef and FinalizationRegistry
WeakRef lets you check whether an object still exists, and FinalizationRegistry runs a callback at some point after an object is collected. The timing is not guaranteed, and the callback may never run. Use them only for optional cleanup or caches, never for logic your program needs to be correct.
Monitoring Memory in Node.js
const v8 = require("node:v8");
const toMB = (b) => (b / 1024 / 1024).toFixed(1);
const { rss, heapUsed, heapTotal } = process.memoryUsage();
console.log(`rss ${toMB(rss)} MB, heap ${toMB(heapUsed)} / ${toMB(heapTotal)} MB`);
console.log(`heap limit ${toMB(v8.getHeapStatistics().heap_size_limit)} MB`);If heapUsed keeps climbing across many requests, you probably have a leak. Run node --inspect app.js to attach DevTools, or call v8.writeHeapSnapshot() to write a snapshot file. Raising the limit with --max-old-space-size=4096 only delays an out-of-memory crash caused by a real leak.
Allocating Less
In hot loops, reuse objects and buffers instead of creating new ones on every pass:
const point = { x: 0, y: 0 };
function sumDistances(xs, ys) {
let total = 0;
for (let i = 0; i < xs.length; i++) {
point.x = xs[i];
point.y = ys[i];
total += Math.hypot(point.x, point.y);
}
return total;
}
console.log(sumDistances([3, 6], [4, 8])); // 15Fewer allocations mean fewer scavenges and shorter pauses.
Exercise
The comparison between snapshots 2 and 3 shows the count of Listener objects rising by 10 each time you open and close a panel 10 times. What do you check next?
Show answer
Select a Listener instance and read its Retainers chain to find the root that still references it, often an event target whose listener was never removed. Then remove the listener on teardown, for example with an AbortController signal.
Exercise
Why does V8 promote surviving objects to the old generation instead of scavenging everything frequently?
Show answer
Most objects die young, so frequent scavenging of the small young generation is cheap. Objects that survive tend to live long, so collecting them less often with mark-and-sweep avoids copying them over and over.