A performance mystery appears when otherwise similar integer and decimal calculations behave differently. V8 can encode small integers directly in the value slot normally used for a memory reference, avoiding heap allocation. This Small Integer representation is invisible to JavaScript but can make common integer operations faster. section 3.0 section 3.4.1
On 64-bit systems, V8 treats integers from -2^31 through 2^31 - 1 as SMIs. Values outside that range, along with fractional values, NaN, and Infinity, require a HeapNumber. A HeapNumber stores a floating-point value in allocated memory, including object overhead, so crossing the SMI boundary can create a performance and memory cliff. section 3.4.1 section 3.4.2
Keeping financial totals integer-scaled
Adding decimal prices makes a running total become a HeapNumber immediately. Representing prices in cents, applying rounded integer tax arithmetic, and dividing by 100 only at the end keeps the loop's total in the SMI-friendly path. This can help in million-element loops, although results vary with engine version, CPU, cache, array size, and optimization tier. section 3.4.3
Use SMI awareness as a targeted optimization rather than a universal rule:
- Keep numeric types consistent in hot loops and arrays; mixing representations can force slower generic handling. section 3.5
- Measure before restructuring code: SMI benefits matter most in tight loops, memory-constrained environments, and systems needing predictable performance. section 3.4.3
- Do not force SMI arithmetic when decimal precision or ordinary application clarity matters more than a runtime-specific optimization. section 3.4.3
Listing 3.1 V8’s internal decision process (simplified)
// V8's Internal Decision Process (simplified)
function howV8StoresNumber(value) {
// First check: Is it an integer?
if (Number.isInteger(value)) {
// Second check: Does it fit in SMI range?
if (value >= -2147483648 && value <= 2147483647) {
return "SMI: Stored directly, no memory allocation";
} else {
return "HeapNumber: Too large for SMI";
}
} else {
return "HeapNumber: Floating-point values always use heap";
}
}
// Examples showing the hierarchy in action
console.log(howV8StoresNumber(42)); #A
console.log(howV8StoresNumber(-1000)); #A
console.log(howV8StoresNumber(0.0)); #A
console.log(howV8StoresNumber(3.14)); #B
console.log(howV8StoresNumber(NaN)); #B
console.log(howV8StoresNumber(Infinity)); #B
console.log(howV8StoresNumber(2147483648)); #CTrace V8's simplified storage decision for integers, fractions, special numeric values, and values beyond the SMI range. section 3.4.2
