Sub topic 4
Tiered Compilation: Trading Startup Time for Peak Speed
This chapter assumes you know how the engine turns source text into bytecode, how an interpreter such as Ignition executes that bytecode, and what just-in-time (JIT) compilation means in general. You should also be comfortable running scripts with Node.js from the command line. Hidden classes, inline caches, and type feedback appear here only by name. Later chapters cover them in detail.
The core tension
Every JavaScript engine faces two goals that pull against each other:
- Fast startup. A web page or CLI tool should begin doing useful work within milliseconds. Most functions run only once or a few times, so time spent compiling them is mostly wasted.
- High peak performance. A small number of functions, such as a game loop, a JSON transformer, or a sorting comparator, run millions of times. For these, highly optimized machine code is worth almost any compile cost.
A single compiler cannot serve both goals. A fast compiler produces mediocre code, and a compiler that produces excellent code is slow and uses a lot of memory. Tiered compilation solves this by running several execution engines of increasing sophistication and moving each function up only when it has earned the investment.
V8's four tiers
Since 2023, V8 (in Chrome and in Node.js 22 and later) has four tiers.
| Tier | Kind | Input | Compile speed | Code quality | Uses type feedback |
|---|---|---|---|---|---|
| Ignition | Interpreter | Bytecode | None (executes bytecode directly) | Lowest | Collects it |
| Sparkplug | Baseline compiler | Bytecode | Very fast, single pass | Low to moderate | No |
| Maglev | Mid-tier optimizing compiler | Bytecode + feedback | Fast | Good | Yes, speculatively |
| TurboFan | Top-tier optimizing compiler | Bytecode + feedback | Slow | Best | Yes, aggressively |
Ignition: the starting point
All code starts in Ignition. Ignition does not generate machine code, so it has no compile cost beyond producing bytecode. While it runs, it records feedback about the types and object shapes each operation sees. The higher tiers depend on that record.
Sparkplug: removing interpreter overhead
Sparkplug, added in 2021, translates bytecode directly into machine code in one linear pass. It does no analysis and no optimization. Each bytecode becomes a fixed snippet of machine code, which is often just a call to the same built-in helper the interpreter would have used.
Sparkplug still pays off because it removes the interpreter's dispatch cost: decoding each bytecode, jumping to its handler, and decoding its operands. Sparkplug also keeps Ignition's stack frame layout, so moving between the two tiers is cheap. That compatibility is also its limit. Sparkplug cannot keep values in registers across bytecodes or specialize on types.
Maglev: optimization on a budget
Maglev, enabled in Chrome 117 in 2023, filled a gap between Sparkplug and TurboFan. It builds an intermediate representation in SSA form (static single assignment, where each value is assigned exactly once). It uses type feedback to emit specialized code, for example a direct field load for a known object shape in place of a generic property lookup. It inserts checks that trigger deoptimization if its assumptions turn out wrong.
Maglev deliberately skips expensive analyses. It compiles about ten times faster than TurboFan, and its code is often good enough that a function never needs to go further.
TurboFan: peak performance
TurboFan does the heavy work: aggressive inlining, escape analysis, redundant-check elimination, loop optimizations, and careful register allocation. Its compile times are long, and it uses enough memory that V8 compiles on background threads to avoid blocking the main thread. TurboFan is used only for functions that are clearly hot and whose feedback has stabilized.
How the engine decides to tier up
V8 does not count calls in a simple way. Each function has an interrupt budget, roughly proportional to its bytecode size. Executing the function, including each backward jump in its loops, spends the budget. When the budget runs out, the runtime checks the function's state and decides whether to move it up a tier. Several things shape that decision:
- Function size. Large functions get larger budgets, because optimizing them costs more.
- Feedback stability. If type feedback is still changing, optimizing now would likely cause a deoptimization soon after. V8 can wait.
- Prior deoptimizations. A function that keeps deoptimizing may be optimized less eagerly, or eventually not at all.
The exact thresholds change between V8 versions and are tuned against real web workloads. Treat them as implementation details, not something to code against.
On-stack replacement
A function called once that contains a loop running a billion iterations never gets another call that could start in optimized code. On-stack replacement (OSR) handles this. V8 compiles an optimized version of the function while the loop is running, then moves the live frame (local variables, loop counter, accumulator) into the new code partway through the loop. Both Maglev and TurboFan support OSR.
Going down: deoptimization and code flushing
Tiering also moves downward. When an optimized function's assumptions fail, V8 deoptimizes: it rebuilds an interpreter frame and continues in Ignition. A later chapter covers this in detail. Separately, V8 can flush the bytecode of functions that have not run for a long time to reclaim memory, and recompiles them lazily if they run again.
Watching the tiers in action
The script below runs a numeric loop many times. You can time it with different tiers enabled or disabled.
// tiers.js
function sumOfSquares(n) {
let total = 0;
for (let i = 0; i < n; i++) {
total += i * i;
}
return total;
}
const start = performance.now();
let result = 0;
for (let run = 0; run < 2000; run++) {
result += sumOfSquares(10000);
}
const elapsed = performance.now() - start;
console.log(`result=${result} time=${elapsed.toFixed(1)} ms`);Run it under several configurations:
# All tiers (default)
node tiers.js
# Interpreter only: no machine code is generated at all
node --jitless tiers.js
# Ignition + Sparkplug only
node --no-maglev --no-turbofan tiers.js
# Everything except the top tier
node --no-turbofan tiers.js
# See tier-up decisions as they happen
node --trace-opt tiers.jsFlag names differ between versions. Older V8 releases used --no-opt in place of --no-turbofan, and Maglev does not exist before V8 11. Check what your Node.js supports with:
node --v8-options | grep -E "sparkplug|maglev|turbofan|jitless"The results usually follow a clear pattern. --jitless is many times slower. Sparkplug alone recovers part of the gap. Maglev gets close to full speed. TurboFan gains the rest on a hot numeric loop like this one. In the --trace-opt output, look for lines that mark sumOfSquares for optimization and name the target tier, along with OSR entries for the top-level loop.
Trade-offs and failure modes
Tiering is a heuristic, and heuristics misjudge some workloads:
- Short-lived processes such as CLI tools, serverless cold starts, and test runners may end before hot code reaches TurboFan. Most of their time is spent in Ignition, Sparkplug, and Maglev. Baseline tiers and code caching matter more for them than peak optimization.
- Benchmarks that never warm up measure the low tiers. Benchmarks that only measure after warm-up hide the startup cost real users pay.
- Unstable feedback can make a function optimize, deoptimize, and re-optimize repeatedly. Each cycle burns compile time without delivering lasting speed.
- Memory pressure. Every tier's code takes memory, which is why V8 discards optimized code and flushes bytecode for cold functions.
- Jitless environments. Some platforms forbid writable executable memory. With
--jitless, V8 runs Ignition only, and code that relies on the optimizers becomes much slower.
The engine usually makes good choices for typical code. Your main influence over tiering is indirect: write code whose types and shapes stay consistent, so that feedback settles quickly and optimizations hold.
Exercise
A Node.js script runs a single function call containing a loop of 500 million iterations. The function is never called again. Explain how that function can still end up running TurboFan code, and name the mechanism.
Show answer
The loop's backward jumps spend the function's interrupt budget even though the function is called only once. When the budget runs out, V8 compiles an optimized version (Maglev, then possibly TurboFan) and uses on-stack replacement (OSR) to move the running frame, with its live locals and loop counter, into the optimized code partway through the loop.
Exercise
Why does Sparkplug improve performance even though it performs no optimizations, and why is it cheap to switch between Ignition and Sparkplug?
Show answer
Sparkplug removes the interpreter's dispatch overhead (decoding each bytecode and jumping to its handler) by emitting straight-line machine code for each bytecode. It keeps the same stack frame layout as Ignition, so V8 can move between the two tiers without translating frames.
Exercise
You benchmark a serverless handler that runs for about 50 ms per cold start and find that disabling TurboFan barely changes its latency. Is this surprising? What does it suggest about where to focus?
Show answer
It is not surprising. In a 50 ms process, little or no code gets hot enough to reach TurboFan, so most execution happens in Ignition, Sparkplug, and Maglev. Startup costs such as parsing, lazy compilation, and module loading, plus code caching or snapshots, are likely to matter more than peak-tier optimization.