Optimization changes an implementation to improve execution efficiency while preserving required behavior. JavaScript engines may keep the same specification-level behavior while choosing faster internal representations for predictable code. Unpredictable object structures, types, and access patterns can instead trigger slower modes or deoptimization. section 5.10 section 3.4
V8 commonly begins functions in Ignition and incrementally optimizes frequently executed code. With on-stack replacement, it can compile a hot loop while that loop runs, transfer its current variables and loop state, and continue in optimized code without restarting. The optimized form remains useful only while its recorded type assumptions hold; an unexpected type or previously untouched branch can cause deoptimization. section 6.6.4 section 7.4.1
Practical optimization rules follow from the engine’s observed execution patterns:
- Keep object structures and property-access patterns predictable so optimized representations remain applicable. section 5.10
- Do not assume try-catch itself prevents optimization; an unvisited catch path matters because entering it later changes the observed behavior. section 7.4.1
- Avoid repeated implicit conversions in hot operations when explicit type handling can remove conversion work. section 4.4.4
- Treat engine-specific speedups as conditional: small-integer arithmetic may be faster, but only within the relevant representation boundaries. section 3.4
A hot function that deoptimizes
A function repeatedly called with values from 0 through 10,000 can optimize even when it contains try-catch. Calling it later with 10,001 exercises the previously unseen throwing path and triggers deoptimization—not because throwing is inherently unoptimizable, but because execution changed. section 7.4.1
function doSomething(val) {
try {
if (val < 0 || val > 10_000) {
throw new Error('Out of range!');
}
} catch (err) {
console.log('oops! Out of range!');
}
}
for (let n = 0; n < 10_000; n++) {
doSomething(n); // Function will optimize!
}
doSomething(10_001); // Deoptimization!Inspect the runnable loop that demonstrates optimization followed by deoptimization when an out-of-range input reaches a previously unexecuted path. section 7.4.1





































