Skip to content

Generational GC

V8 (and most modern JS engines) uses a generational approach to garbage collection. The insight: most objects die young (“the generational hypothesis”).

Newly created objects live here:

function process() {
// These objects are created in the young generation
const temp = { data: 'temporary' };
const result = temp.data.toUpperCase();
return result;
// Both 'temp' and the upper case string are likely
// collected in the next minor GC
}
  • Small region of memory
  • Collected frequently (minor GC)
  • Uses Scavenge algorithm (fast copy collector)
  • Objects surviving 2 GC cycles → promoted to old generation

Long-lived objects live here:

// These objects survive and get promoted
const appConfig = { theme: 'dark', lang: 'en' };
const cache = new Map();
function setup() {
const handler = () => console.log('ready');
window.addEventListener('load', handler);
// handler survives because it's referenced by the event system
}
  • Larger region of memory
  • Collected infrequently (major GC)
  • Uses Mark-Sweep-Compact algorithm
  • More expensive to collect
flowchart LR
subgraph "Young Generation (Nursery)"
New["New Objects\nfrequent GC"]
Surviving["Surviving Objects\npromoted after 2 GCs"]
end
subgraph "Old Generation"
Old["Long-lived Objects\ninfrequent major GC"]
end
New -->|"Minor GC (Scavenge)"| Surviving
Surviving -->|"Promotion"| Old
Old -->|"Major GC (Mark-Sweep-Compact)"| Final
AspectYoung GenOld Gen
SizeSmall (~8MB)Large (rest of heap)
GC frequencyFrequentInfrequent
GC speedFast (~ms)Slower (~ms to 100ms)
AlgorithmScavenge (copy)Mark-Sweep-Compact
Most objectsDie hereSurvive here

Modern V8 performs GC work incrementally and concurrently to avoid long pauses:

  • Incremental: Break GC work into small chunks between JS tasks
  • Concurrent: GC work runs in parallel with your code (multi-core)

This means you rarely notice GC pauses in modern browsers.

  • Create objects only when needed (avoid temporary objects in hot loops)
  • Reuse objects rather than creating new ones
  • Large caches can cause old gen GC pressure
  • Modern V8 handles most patterns well