Feedback → specialization → deopt09 / 19

Optimization relies on assumptions

What changes when code that handled numbers receives a string.

If add(a, b) frequently receives numbers, the optimizing compiler may prepare a specialized execution path with assumption checks. This can make a dynamic language faster while preserving its rules.

function add(a, b) { return a + b; }
add(2, 3);     // 5
add('2', 3);   // '23'

When an assumption fails, execution may take another path or use deoptimization: restoring the state needed by less specialized code. The program must still return '23' rather than perform an incorrect numeric addition.

After repeated calls with numbers V8 may generate machine code for numeric addition

That code checks the assumption that a and b are numbers.

add(2, 3) ✓ Check passed

Both arguments are numbers.

Numeric addition

The prepared machine code runs.

Result · number5
add('2', 3) × Check failed

The first argument is a string.

Deoptimization is possible

V8 restores the state and continues execution through Ignition.

Result · string'23'
This is one possible scenario. Passing a string does not necessarily cause deoptimization: the function may have another suitable execution path.

Object shapes and inline caches also provide feedback. We will examine them in the section on optimization.

Before changing dynamic-object code for JIT performance, record a profile, identify an expensive part of the program, and determine why it is expensive.

Key takeaway

Deoptimization preserves program behavior when the assumptions of optimized code no longer hold.

Check the primary source ↗

V8 · Maglev↗Execution tiers, feedback, and speculative optimization.V8 · Maps / Hidden Classes↗Feedback about object shapes and the assumptions behind optimized code.ECMA-262 · Addition↗The semantics of numeric addition and string concatenation.