Sub topic 14
Inside the Optimizing Compiler: Inlining and Escape Analysis
This chapter assumes you already know how speculative optimization works: TurboFan reads type feedback, compiles code that assumes that feedback still holds, and deoptimizes when it stops holding. It also assumes you can run Node.js with --allow-natives-syntax. Two transformations explain much of the speed gap between optimized and unoptimized JavaScript. Inlining removes function call boundaries. Escape analysis removes object allocations that never leave a function.
Why These Two Belong Together
Most optimizations work inside one function. A call to another function blocks them, because the compiler cannot see what happens past it. Inlining copies the callee's body into the caller, which gives later passes a single, larger piece of code to analyze. Escape analysis benefits most from this: a temporary object that crosses a call boundary looks like it escapes, but once the callee is inlined the compiler can see that it does not.
Inlining
How TurboFan decides what to inline
TurboFan does not inline based on function size alone. It uses the call feedback in the caller's feedback vector, which records which function objects a call site has actually called.
| Call site feedback | Inlining outcome |
|---|---|
| Monomorphic: one target seen | Inlined if within size budget, guarded by a target check |
| Polymorphic: a few targets | Each target may be inlined behind a dispatch on the target |
| Megamorphic or no feedback | Not inlined; a generic call is emitted |
| Never executed | Usually not inlined; may compile to a deopt point |
Size limits apply as well. V8 has flags such as --max-inlined-bytecode-size (per callee, around 460 bytes of bytecode by default) and --max-inlined-bytecode-size-cumulative (a total budget for each optimized function). These defaults change between versions, so treat the numbers as an order of magnitude and do not tune your code to them. Small, hot functions are the ones that get inlined. A large function called once from a loop usually is not.
Recent V8 versions let Maglev, the mid-tier compiler, inline small functions too. TurboFan still inlines more aggressively.
Watching inlining happen
// Run with: node --allow-natives-syntax --trace-turbo-inlining inline.js
function square(x) {
return x * x;
}
function sumSquares(n) {
let s = 0;
for (let i = 0; i < n; i++) {
s += square(i);
}
return s;
}
%PrepareFunctionForOptimization(sumSquares);
sumSquares(10);
sumSquares(10);
%OptimizeFunctionOnNextCall(sumSquares);
console.log(sumSquares(1000)); // 332833500The trace prints lines that name square as an inlining candidate for sumSquares and report whether it was inlined. The exact wording differs between Node versions. The two warm-up calls exist so the call site in sumSquares records feedback pointing at square. Without that feedback, TurboFan has no target to inline.
What inlining enables
After square is inlined, s += i * i is a plain multiply-add inside the loop. The compiler can drop the call overhead (frame setup, argument passing, return), apply type specialization across the old boundary, and fold constants. For example, square(3) inside an inlined context becomes 9.
Gotchas
- Inlined frames still exist logically. Stack traces show
squareeven when its code was inlined, because V8 keeps metadata that maps optimized code back to source frames. - Deoptimization gets more expensive. If an inlined callee's assumption fails, the deoptimizer must rebuild one interpreter frame for every inlined function on the path.
- Changing the target defeats it. Reassigning
square = otherFnmakes the call site's feedback polymorphic or causes a deopt at the target check. - Function.prototype.apply, bind and spread are inlined in many common forms, but unusual uses can fall back to generic calls. Measure before you assume either way.
Escape Analysis
The idea
An object escapes when a reference to it can be observed outside the current compilation unit. That happens when it is returned, stored into another object or a global, passed to a call that was not inlined, or captured by a closure that outlives the function. An object that does not escape needs no heap allocation. TurboFan can apply scalar replacement: each field becomes an ordinary local value, often held in a register.
class Vec {
constructor(x, y) {
this.x = x;
this.y = y;
}
length() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
}
function distance(x1, y1, x2, y2) {
const d = new Vec(x2 - x1, y2 - y1); // temporary
return d.length();
}
let total = 0;
for (let i = 0; i < 1e6; i++) {
total += distance(0, 0, i, i);
}
console.log(total.toFixed(2));Once distance is optimized, the Vec constructor and length are inlined. Escape analysis then sees that d is only read locally. The allocation, the hidden-class setup and the property loads all disappear. What remains is Math.sqrt(dx*dx + dy*dy) on two numbers. You get the readability of a small class with no allocation cost in the hot path.
Making it escape
const seen = [];
function distanceLogged(x1, y1, x2, y2) {
const d = new Vec(x2 - x1, y2 - y1);
seen.push(d); // d is now reachable from a global: it escapes
return d.length();
}A single store into a long-lived structure forces a real allocation. A store that only happens rarely, such as logging inside an if (debug) branch that has never run, usually does not, because TurboFan replaces the untaken branch with a deopt point.
Deoptimizing a removed object
What happens if code deoptimizes while d exists only as two registers? The interpreter expects a real object. V8 records how to materialize it: the deoptimizer allocates the Vec at bailout time, using the saved field values and the correct hidden class. This is correct but slow, so a function that keeps deoptimizing loses most of the benefit.
Common escape causes
| Pattern | Escapes? |
|---|---|
| Object read locally, methods inlined | No |
| Object returned from the optimized function | Yes, unless the caller is also inlined into an outer optimized function |
| Stored into an array, global or another escaping object | Yes |
| Passed to a non-inlined function | Yes |
| Captured by a closure that is returned or stored | Yes |
| Used in a branch that never ran during warm-up | Usually no, since the branch becomes a deopt point |
Decision Criteria
Do not restructure code for the inliner. Small, single-purpose functions with stable argument types and stable call targets are already what it handles best. Profile allocation in hot loops, for example with --trace-gc or a heap profiler. If short-lived objects dominate, check whether they escape through a store, a closure or a non-inlined call. Only rewrite to plain variables when the profiler shows a real cost, and leave a comment explaining why.
Exercise
In the Vec example, someone adds forty lines of validation and logging to Vec.prototype.length. Allocation counts in the hot loop rise sharply. Explain the likely chain of cause and effect.
Show answer
The larger length method probably exceeds TurboFan's inlining bytecode budget, so it is no longer inlined into distance. The call to d.length() becomes a real call that receives d as its receiver. Escape analysis then has to treat d as escaping, scalar replacement no longer applies, and every iteration allocates a Vec on the heap.
Exercise
Why does TurboFan need call-site feedback to inline a function, instead of just inlining whatever the source code names?
Show answer
In JavaScript a name like square is a variable whose value can change at runtime, so the source does not fix the call target. Feedback records which function objects were actually called. TurboFan inlines those targets behind a cheap check and deoptimizes if a different target appears. Without feedback it has nothing to speculate on.
Exercise
An optimized function has scalar-replaced a temporary object, and then a type check fails and the function deoptimizes. What must the deoptimizer do with that object?
Show answer
It must materialize the object. Using metadata TurboFan recorded at compile time, it allocates a real heap object with the correct hidden class and fills in the field values held in registers or stack slots, so the interpreter frame it rebuilds can refer to the object.