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.
That code checks the assumption that a and b are numbers.
add(2, 3)
✓ Check passed
Both arguments are numbers.
The prepared machine code runs.
5add('2', 3)
× Check failed
The first argument is a string.
V8 restores the state and continues execution through Ignition.
'23'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.