Sub topic 3
Speculative Optimization: Betting on Past Behavior
This chapter assumes you have read the earlier chapters on tiered compilation, hidden classes, and inline caches. It also assumes you can run Node.js from the command line.
Speculative Optimization
The optimizing compilers (Maglev and TurboFan) read the type feedback that the interpreter collected. If a + b has only ever seen small integers, the compiler emits integer addition. Before that addition it places a cheap type check, called a guard. The compiler is betting that the future will look like the past.
Deoptimization: When the Bet Fails
When a guard fails, V8 throws away the optimized frame. It rebuilds the interpreter state for that point in the function and continues in bytecode. If this repeats, the function may be reoptimized with more general assumptions.
// Run with: node --trace-opt --trace-deopt add.js
function add(a, b) {
return a + b;
}
for (let i = 0; i < 1000000; i++) {
add(i, i); // feedback says: small integers
}
add('a', 'b'); // breaks the integer assumptionArray Elements Kinds
Each array has an elements kind, and transitions only move toward more general kinds:
const arr = [1, 2, 3]; // PACKED_SMI_ELEMENTS
arr.push(4.5); // PACKED_DOUBLE_ELEMENTS
arr.push('x'); // PACKED_ELEMENTS
arr[10] = 1; // HOLEY_ELEMENTSRemoving the string later does not move the array back to a more specific kind.
Inlining and Escape Analysis
Inlining copies a small callee into its caller, so the optimizer can analyze both together. Escape analysis finds objects that never leave the function and replaces them with local values, which removes the allocation.
Watching the Engine
| Tool | Shows |
|---|---|
| `--trace-opt` / `--trace-deopt` | When functions are optimized or deoptimized |
| `%HaveSameMap(a, b)` | Whether two objects share a hidden class |
| `%HasFastProperties(o)` | Whether an object is in dictionary mode |
| `%DebugPrint(x)` | The map and elements kind |
The % functions require --allow-natives-syntax.
Engine-Friendly JavaScript
- Initialize every property in the constructor, in the same order each time.
- Keep each variable and array to one value type.
- Avoid
deleteand arrays with holes in hot code. - Profile first, and change code only where the profile shows a cost.
Beyond V8
SpiderMonkey and JavaScriptCore use the same core ideas under different names. SpiderMonkey has shapes, CacheIR inline caches, and the Warp optimizing compiler. JavaScriptCore calls hidden classes "structures" and runs four tiers: LLInt, Baseline, DFG, and FTL.
Exercise
An optimized function deoptimizes every time it receives an occasional null argument. Why does this happen, and what is one fix?
Show answer
The optimizer guarded on the object shape it had seen, so the null fails the guard. Handle null before the hot path, or pass a consistent placeholder object, so the call site keeps seeing one type.