open atlas
↑ Back to track
JavaScript Engine internals JSE · 05 · 03

When V8 allocates a Context (and what it costs)

V8 allocates a Context only when an inner function captures a variable; otherwise variables stay in registers, free. A let loop whose body captures the binding allocates a fresh Context per iteration — real cost in hot loops. How to minimise captures.

JSE Middle ◷ 14 min
Level
FoundationsJuniorMiddleSenior

You change a for (var i …) to for (let i …) because a linter told you to, and a microbenchmark that builds a million callbacks gets measurably slower. Nothing about your logic changed. What changed is that let gives each iteration its own binding — and when the body captures that binding, V8 must allocate a brand-new heap Context on every single turn of the loop. The semantics you wanted came with an allocation you didn’t see.

The allocation rule: capture, nothing else

A Context is not allocated because you opened a function or a block. It is allocated only when the compiler determines that a variable in that scope is captured by an inner function — referenced by a nested function or arrow that may outlive the current frame. If no inner function closes over anything, the scope needs no Context at all: its variables live in registers or stack slots and cost nothing beyond the frame.

This is the single most important cost model in this unit. Most functions you write allocate zero Contexts, because they either define no inner functions or define inner functions that capture nothing. The cost appears precisely at capture.

function noCapture(xs) {
  let sum = 0;
  for (let i = 0; i < xs.length; i++) sum += xs[i];
  return sum;            // no inner function -> no Context, all registers
}

function capture(xs) {
  let sum = 0;
  xs.forEach(x => sum += x); // the arrow captures 'sum' -> 'sum' context-allocated
  return sum;                // one Context for this scope
}

The per-iteration trap: let in a loop + capture

let and const declared in a for loop header create a fresh binding per iteration. This is the feature that makes the classic “all my callbacks print the last value” bug go away. But the implementation has a cost when the body captures that binding.

const fns = [];
for (let i = 0; i < n; i++) {
  fns.push(() => i);   // captures THIS iteration's 'i'
}
// Each callback returns its own i: fns[3]() === 3. Correct!
// But: a NEW Context is allocated for each iteration to hold that iteration's i.

For the closures to each see a different i, each iteration’s i must live somewhere distinct — so V8 allocates a fresh Context per iteration and copies the binding in. With n large and the body capturing, that is n heap allocations and n objects for the GC to trace. Contrast var, which has one binding for the whole loop:

const fns = [];
for (var i = 0; i < n; i++) {
  fns.push(() => i);   // all capture the SAME 'i'
}
// Every callback returns the final i (=== n). One binding, one Context.

var allocates at most one Context here (still one, because the binding is captured) — but it does not multiply by n. The widely-repeated advice “always use let” is correct for correctness, but in a genuinely hot loop that creates closures, the per-iteration Context is a real, measurable cost.

Context allocations by pattern (loop of n)
Loop, no inner function
0 Contexts
Loop body captures, `var i`
1 Context total
Loop body captures, `let i`
n Contexts (1/iter)
Inner fn captures nothing
0 Contexts
Forces a Context: eval / with
always
GC objects to trace from n closures
scales with n

What forces a Context, and how to minimise it

Things that force context allocation: any closure over a variable, a with block, a direct eval (it can read/declare locals), and in some cases observing arguments in ways that defeat analysis. The levers to reduce it on hot paths:

  • Hoist the closure out of the loop. If the callback does not actually need each iteration’s binding, define it once outside the loop. No per-iteration Context.
  • Pass data as arguments instead of capturing. A function that receives x as a parameter does not capture it; parameters are cheaper than a captured Context slot and keep the call shape predictable (next lesson).
  • Use an index, not a captured binding, when you only need the value at call time. Sometimes a plain for with var plus an explicit copy is the right tool in a million-iteration hot loop — measure it.
  • Keep big or long-lived data out of captured scopes (the retention lesson) — a separate concern from allocation count but the same discipline.

Applied together, these four levers reduce both the number of Context objects the GC must trace and the number of heap allocations per hot iteration. Without hoisting, even a trivial () => i inside a tight loop silently multiplies allocations by n — the kind of cost that only shows up in an allocation profile, not in a code review.

// Hot path: avoid n per-iteration Contexts when capture isn't needed.
function attach(handlers, fn) {            // fn defined ONCE, captures nothing per-iter
  for (let i = 0; i < handlers.length; i++) handlers[i].on(fn);
}
Quiz

`for (let i = 0; i < n; i++) cbs.push(() => i);` — how many Contexts does V8 allocate for the loop, and why?

Quiz

A hot loop pushes a callback that does NOT need each iteration's value. What is the cheapest fix?

Order the steps

Order these loops by Context allocations for n iterations, from zero allocations to the most.

  1. 1 Loop summing into a local, no inner function (0 Contexts)
  2. 2 Loop capturing a `var` binding in a callback (1 Context)
  3. 3 Loop capturing a per-iteration `let` binding (n Contexts)
  4. 4 Loop with a `with` block plus per-iteration capture (n Contexts, all unoptimisable)
Edge cases

V8 is not naive about this: if a loop body’s closure provably does not escape and the binding is not actually observed per-iteration, the optimiser can sometimes avoid materialising distinct Contexts. But you cannot rely on it — escape analysis is fragile and bails on many real shapes. Treat per-iteration capture as “n allocations until proven otherwise”, and verify hot paths with --trace-gc or an allocation profile rather than trusting the optimiser to save you.

Recall before you leave
  1. 01
    What exactly triggers a Context allocation, and what does not?
  2. 02
    Why can `for (let …)` be slower than `for (var …)` when the body creates closures, and is that a reason to avoid let?
  3. 03
    How do you minimise context allocation on a hot path?
Recap

The cost model of scoping in V8 reduces to one rule: a Context is allocated only when an inner function captures a variable. Functions with no inner functions, or whose inner functions capture nothing, allocate zero Contexts and keep everything in registers and stack slots. The expensive and easy-to-miss case is a loop whose body captures a per-iteration let/const binding: because each iteration needs its own binding to preserve the correct distinct-value semantics, V8 allocates a fresh Context every iteration — n iterations, n heap objects, n things for the GC to trace — whereas the equivalent captured var shares a single binding and a single Context. with and direct sloppy eval also force a Context and additionally defeat optimisation. To stay cheap on hot paths: define closures once outside loops when per-iteration state is not needed, pass data as arguments rather than capturing it, and reserve per-iteration capture for where the semantics genuinely require it. V8’s escape analysis can sometimes elide these allocations but is unreliable, so measure with an allocation profile. Minimising captures also sets up the next lesson — fewer, more uniform closures keep call sites monomorphic. Now when you profile a hot loop and see unexpectedly high allocation pressure, count the closures created per iteration before reaching for anything else — a captured let is often the whole story.

Practice

Start at the top. Tasks go easiest → hardest: recall a fact, apply it to a case, then a senior-level stretch. Open one, attempt it, then reveal.

recallapplystretch0 of 8 done
Connected lessons
appears again in184

Something unclear?

Ask a question about this lesson. Questions are anonymous and go straight to the author to make the lesson better.

shortcuts expand
search
K
prev piece
k
next piece
j
cycle tier
t
this menu
?
sources3
expand
  1. 01
  2. 02
  3. 03

Trademarks belong to their respective owners. Editorial reference only.