Sub topic 10
Generational Collection: Young and Old Generations
This chapter assumes you already know how mark-and-sweep works: the collector starts from roots, marks every reachable object, and frees the rest. You should also be able to run a script with Node.js from the command line. Here you will see how V8, the engine in Chrome and Node.js, splits the heap by object age so that most collections are fast and touch only a small part of memory.
The Problem with Marking Everything
A plain mark-and-sweep collector visits every live object each time it runs. On a heap holding 1 GB of long-lived data, it walks that whole gigabyte even when the only garbage is a few thousand temporary objects created in the last few milliseconds. The cost of each collection grows with the amount of live data, and live data is usually the part that has not changed.
Generational collection avoids that cost by betting on a pattern seen in almost every program.
The Generational Hypothesis
The generational hypothesis says that most objects die young. Look at what typical JavaScript allocates:
- Intermediate results inside a loop, such as
{ x, y }points or array slices. - Strings built while formatting a log line.
- Closures passed to
map,filter, orthenthat run once and are discarded. - Parsed request bodies that live only for one HTTP request.
These objects become unreachable within microseconds or milliseconds. A smaller group of objects lives for a long time: module state, caches, the DOM tree, server configuration. Few objects fall in between.
If the hypothesis holds, the collector can split the heap into a small area for new objects and a large area for objects that have proven they last. It can then collect the small area often and cheaply, and the large area rarely.
V8's Heap Layout
V8 divides the managed heap into several spaces. The two that matter for this chapter are the young generation and the old generation.
| Space | What lives there | Collected by | Typical frequency |
|---|---|---|---|
| Young generation (new space) | Newly allocated, small objects | Scavenger (minor GC) | Very often, many times per second under load |
| Old generation (old space) | Objects that survived young collections | Mark-Compact (major GC) | Rarely, when old space grows |
| Large object space | Objects too big to copy cheaply, such as huge arrays | Major GC | With the old generation |
| Code space | Compiled machine code | Major GC | With the old generation |
The young generation is small, usually somewhere between a few MB and a few tens of MB depending on the V8 version, the platform, and available memory. The old generation can grow to gigabytes. The next chapter on Node.js covers the old-generation limit and how to raise it.
Minor GC: The Scavenger
The young generation is split into two equal halves called semi-spaces. At any moment, one is the from-space, where new objects are allocated, and the other, the to-space, is empty.
Allocation in from-space is a bump-pointer operation. V8 keeps a pointer to the next free byte, and allocating an object moves the pointer forward by the object's size. No free list has to be searched, which is why creating short-lived objects in JavaScript is cheap.
When from-space fills up, V8 runs a scavenge:
- Start from the roots, plus any old-generation objects that point into the young generation (covered below).
- Copy each reachable young object into to-space, or into the old generation if it has already survived a previous scavenge.
- Leave a forwarding address in the old location so other references to the same object can be updated to point at the new copy.
- Scan the copied objects for further young references and copy those as well.
- Swap the roles: to-space becomes the new from-space, and the old from-space is treated as empty.
Step 5 is the key point. The scavenger never touches dead objects. It copies the survivors and then throws away the entire semi-space at once. The cost depends on how many objects survive, not how many were allocated. If 99% of the young generation is garbage, the scavenge copies only 1%.
Copying also compacts. Survivors end up packed together in to-space, so there is no fragmentation in the young generation.
Promotion to the Old Generation
An object that survives one scavenge is copied within the young generation. If it survives a second scavenge, V8 promotes it, meaning it copies the object into the old generation. The reasoning is that an object that has lived through two collections is likely to keep living, so copying it back and forth between semi-spaces would waste work.
Major GC: Mark-Compact
The old generation is collected by V8's Mark-Compact collector, a major GC. It is the mark-and-sweep algorithm from the earlier chapter with an extra compaction phase:
- Mark: trace from the roots and mark every reachable object in the whole heap.
- Sweep: record the memory of unmarked objects as free space that future promotions can reuse.
- Compact: for heavily fragmented memory pages, move live objects together and update references to them, so whole pages can be released.
Copying the entire old generation the way the scavenger does would be too expensive and would need twice the memory. That is why the old generation uses a different algorithm. V8 does most of the marking concurrently on background threads and sweeps lazily, so a major GC rarely means a long single pause. It is still far more work than a scavenge.
The Write Barrier and Remembered Sets
A scavenge collects only the young generation, but an old object can hold a reference to a young one:
const cache = new Map(); // long-lived, will be promoted to old space
function remember(key) {
cache.set(key, { createdAt: Date.now() }); // a young object referenced from old space
}If the scavenger looked only at roots, it would miss the reference from cache to the new object and wrongly treat that object as garbage. Scanning the whole old generation to find such references would defeat the point of a minor GC.
V8 solves this with a write barrier. Every time compiled code stores a reference into an object field, a small piece of extra code checks whether an old object now points to a young one. If it does, V8 records that slot in a remembered set. During a scavenge, the remembered set is treated as an extra set of roots.
The write barrier has a small cost on every pointer store. Programs that keep writing fresh objects into long-lived structures pay that cost repeatedly and also grow the remembered set, which makes each scavenge slower.
Watching the Generations Work
The script below allocates many short-lived objects and keeps a few long-lived ones. The temporary objects are pushed into an array so that the optimizing compiler cannot remove the allocations through escape analysis, an optimization that skips allocating objects that never leave a function.
// gc-demo.js
const retained = [];
function work(iteration) {
const batch = [];
for (let i = 0; i < 50_000; i++) {
batch.push({ x: i, y: i * 2 }); // short-lived: garbage after this call
}
if (iteration % 20 === 0) {
retained.push(new Array(5_000).fill(iteration)); // long-lived: survives and is promoted
}
return batch.length;
}
let total = 0;
for (let i = 0; i < 400; i++) {
total += work(i);
}
console.log(`allocated ${total} temporary objects, retained ${retained.length} arrays`);Run it with GC tracing:
node --trace-gc gc-demo.jsYou will see many lines beginning with Scavenge and, depending on heap growth, a few with Mark-Compact. Each line shows heap size before and after the collection and the pause time in milliseconds. Scavenges usually take a fraction of a millisecond to a few milliseconds.
To count collections from inside a program, Node.js exposes GC events through perf_hooks:
// gc-count.js
const { PerformanceObserver, constants } = require("node:perf_hooks");
const counts = { minor: 0, major: 0, other: 0 };
const time = { minor: 0, major: 0 };
const observer = new PerformanceObserver((list) => {
for (const entry of list.getEntries()) {
const kind = entry.detail.kind;
if (kind === constants.NODE_PERFORMANCE_GC_MINOR) {
counts.minor++;
time.minor += entry.duration;
} else if (kind === constants.NODE_PERFORMANCE_GC_MAJOR) {
counts.major++;
time.major += entry.duration;
} else {
counts.other++;
}
}
});
observer.observe({ entryTypes: ["gc"] });
const keep = [];
for (let round = 0; round < 300; round++) {
const temp = Array.from({ length: 20_000 }, (_, i) => ({ i }));
if (round % 10 === 0) keep.push(temp); // some batches survive long-term
}
setTimeout(() => {
observer.disconnect();
console.log(counts);
console.log(`minor ${time.minor.toFixed(1)} ms, major ${time.major.toFixed(1)} ms`);
}, 100);The setTimeout gives the observer time to deliver its buffered entries before the summary prints. Expect minor collections to outnumber major ones by a wide margin.
Failure Modes and Gotchas
Middle-aged objects
The hypothesis breaks for objects that live just long enough to survive two scavenges and then die. Examples include request objects in a slow server, or batches held across a few await points. These objects get copied twice, promoted, and then become garbage in the old generation, where only a major GC can reclaim them. This is often called premature promotion. The symptom in --trace-gc output is frequent Mark-Compact runs even though nothing is leaking.
Tuning the young generation
--max-semi-space-size (in MB) makes the young generation larger. A bigger young generation gives objects more time to die before a scavenge, so fewer of them get promoted. The trade-off is that each semi-space uses more memory and a scavenge with many survivors takes longer. Measure with --trace-gc before and after any change. The right value depends on the workload.
node --max-semi-space-size=64 --trace-gc gc-demo.jsLarge objects skip the nursery
Very large allocations, such as a typed array of many megabytes, go straight into large object space. They never get the cheap young-generation treatment, so creating and dropping large buffers in a hot loop triggers major GC work.
Old-to-young pointer churn
Repeatedly storing new objects into a long-lived array or map adds remembered-set entries and write-barrier work. Updating a primitive field in place, or reusing existing objects, avoids this. The final chapter on allocation pressure returns to these patterns.
Exercises
Exercise
Why does the cost of a scavenge depend on the number of surviving objects rather than the number of allocated objects?
Show answer
The scavenger copies only reachable objects out of from-space and then treats the whole semi-space as empty. Dead objects are never visited, so 10,000 or 10 million dead objects cost the same, and only copying survivors takes time.
Exercise
A scavenge only traces the young generation. How does V8 avoid freeing a young object that is referenced only by an old-generation Map?
Show answer
The write barrier runs on every pointer store. When it sees an old object pointing to a young one, it records that slot in the remembered set. The scavenger treats remembered-set entries as roots, so the young object is found and kept.
Exercise
A Node.js service shows frequent Mark-Compact events in --trace-gc output, but heap size after each major GC stays flat at about 300 MB. What is the likely cause, and what could you try?
Show answer
The flat post-GC heap rules out a leak. The likely cause is premature promotion: objects such as per-request data survive two scavenges, get promoted, then die in old space. You could reduce how long those objects live, reuse them, or try a larger --max-semi-space-size and compare the GC trace.