Sub topic 13
Array Elements Kinds and Fast Arrays
This chapter assumes you know how hidden classes describe object shapes and how inline caches use those shapes. It also assumes you can run Node.js with V8 flags such as --allow-natives-syntax. Hidden classes cover an object's named properties, such as point.x. Arrays raise a different question: how does the engine store a list of indexed values such as arr[0] and arr[1] so that reading them stays fast? V8 answers it by tracking an elements kind for every array.
What an Elements Kind Is
An elements kind is a label V8 attaches to an object's indexed storage, which it calls the elements backing store. The label records two facts:
- What type of values the array holds. The options are only small integers, only numbers, or anything at all.
- Whether the array has holes. A hole is an index below
lengththat has no value at all. That is different from holdingundefined.
The elements kind is part of the array's hidden class (its map). Two arrays with different elements kinds therefore have different maps, even if both are plain arrays created with [].
The common kinds
| Elements kind | Values allowed | Storage | Typical cause |
|---|---|---|---|
| `PACKED_SMI_ELEMENTS` | Small integers only | Tagged Smis | `[1, 2, 3]` |
| `PACKED_DOUBLE_ELEMENTS` | Any number | Raw unboxed 64-bit floats | `[1, 2.5]`, `[1, NaN]`, `[-0]` |
| `PACKED_ELEMENTS` | Any value | Tagged pointers | `[1, 'a']`, `[{}]` |
| `HOLEY_SMI_ELEMENTS` | Small integers plus holes | Tagged Smis | `new Array(3)` |
| `HOLEY_DOUBLE_ELEMENTS` | Numbers plus holes | Raw floats with a hole marker | `[1.5, , 2]` |
| `HOLEY_ELEMENTS` | Anything plus holes | Tagged pointers | `['a', , 'b']` |
| `DICTIONARY_ELEMENTS` | Anything, stored sparsely | Hash table | `a[2 ** 30] = 1` |
A Smi ("small integer") is an integer that V8 stores directly in a pointer-sized slot without allocating a heap object. Its range is 31-bit or 32-bit signed, depending on the build. Values outside that range, fractions, NaN, Infinity, and -0 are not Smis. All of them force the double kind.
V8 has more kinds than these, including ones for typed arrays, frozen arrays, and arguments objects. The seven in the table cover ordinary application code.
Transitions Only Go One Way
Elements kinds form a lattice, which is an ordering from most specific to most general. An array can move toward a more general kind. It never moves back, even after you remove the value that caused the change.
The diagram leaves out some shortcuts, such as PACKED_SMI_ELEMENTS going straight to PACKED_ELEMENTS when you push a string. The rule is always the same: more general type, or packed to holey, and never the reverse.
You can watch transitions happen with V8's native test functions:
// Run with: node --allow-natives-syntax kinds.js
const arr = [1, 2, 3];
console.log(%HasSmiElements(arr), %HasHoleyElements(arr)); // true false
arr.push(4.5);
console.log(%HasDoubleElements(arr)); // true
arr.push('x');
console.log(%HasObjectElements(arr)); // true
arr[10] = 1; // indexes 6 through 9 are now holes
console.log(%HasHoleyElements(arr)); // true
arr.length = 3; // drop the string, the double, and the holes
console.log(%HasObjectElements(arr), %HasHoleyElements(arr)); // true trueThe last line shows the one-way rule. After truncation the array holds only 1, 2, 3, but it stays HOLEY_ELEMENTS.
Why Specific Kinds Are Faster
Unboxed doubles
In PACKED_DOUBLE_ELEMENTS, V8 stores raw 64-bit floats side by side, the way a C double[] would. Optimized code can load arr[i] straight into a floating-point register. In PACKED_ELEMENTS, each non-Smi number is a pointer to a separate heap number. Every read has to follow that pointer and check its type.
Smis and type checks
When the optimizing compiler sees that an array is PACKED_SMI_ELEMENTS, it knows every element is a small integer. Arithmetic on those elements needs no type checks and usually no overflow-to-double handling until a sum leaves the Smi range.
The cost of holes
Reading a hole cannot just return undefined. JavaScript requires the engine to look up the index on the prototype chain, because Array.prototype[3] or Object.prototype[3] could exist:
Array.prototype[1] = 'surprise';
const a = [0, , 2];
console.log(a[1]); // 'surprise'
delete Array.prototype[1];V8 keeps a global protector, a flag that stays valid as long as nobody has put indexed properties on the built-in prototypes. While the protector holds, a hole check is cheap. Code for holey arrays still needs that extra check on every read, and packed arrays skip it. If any code in the process does what the snippet above does, the protector becomes invalid and holey reads get slower everywhere.
Out-of-bounds reads
Reading past the end behaves like reading a hole. It triggers a prototype chain lookup and can make the load site's inline cache more generic. The classic off-by-one loop does exactly that:
const items = [1, 2, 3];
let sum = 0;
for (let i = 0; i <= items.length; i++) { // <= reads items[3]
sum += items[i] ?? 0;
}
console.log(sum); // 6The result is correct, but every pass reads one index out of bounds. Use i < items.length or for...of.
Elements Kinds and Inline Caches
The elements kind lives in the map, so a function that receives arrays of different kinds sees different maps at its keyed load site:
function first(list) {
return list[0];
}
first([1, 2, 3]); // PACKED_SMI_ELEMENTS
first([1.5, 2.5]); // PACKED_DOUBLE_ELEMENTS
first(['a', 'b']); // PACKED_ELEMENTS
first([1, , 3]); // HOLEY_SMI_ELEMENTS
// The keyed load in first() has now seen four maps: polymorphic.This is the same monomorphic-to-polymorphic progression you saw with named properties. V8 softens it somewhat. Where it can, it merges feedback toward the more general kind and reuses one handler, because code written for PACKED_ELEMENTS can also read Smi arrays. Doubles are the exception: unboxed and tagged storage need different load code, so mixing them still costs something.
Edge Cases Worth Knowing
Preallocating creates holes
new Array(n) creates an array of length n with no values, so it starts as HOLEY_SMI_ELEMENTS. Filling it later does not make it packed:
// Run with: node --allow-natives-syntax prealloc.js
const pre = new Array(3).fill(0);
console.log(%HasHoleyElements(pre)); // true: still holey after fill
const built = [];
for (let i = 0; i < 3; i++) built.push(0);
console.log(%HasHoleyElements(built)); // false: packedPreallocation avoids resizing the backing store as the array grows, which can still be worth it for large arrays. Weigh that against the holey reads that follow. For big numeric buffers, a typed array such as Float64Array is often the better choice. It has a fixed type and no holes.
Literals remember transitions
V8 tracks array literals through allocation sites. If an array created by a literal transitions, V8 records that on the site. Later arrays from the same literal can then start in the more general kind and skip the transition:
// Run with: node --allow-natives-syntax sites.js
function make() {
return [1, 2, 3];
}
const first = make();
first.push(1.5); // transition recorded on the literal's allocation site
const second = make();
console.log(%HasDoubleElements(second)); // typically trueThis means one array that occasionally gets a double can change how a whole literal site behaves.
Sparse arrays become dictionaries
Writing far past the end, as in a[2 ** 30] = 1 on a short array, makes V8 switch the elements to DICTIONARY_ELEMENTS, a hash table keyed by index. This saves memory for sparse data, but every access becomes a hash lookup. %HasDictionaryElements(a) confirms the switch. If your keys really are sparse, a Map states that intent more clearly.
`delete` leaves a hole
delete arr[i] does not shift elements. It leaves a hole and moves the array to a holey kind permanently. Use splice or build a new array instead.
Practical Guidelines
- Keep an array's element types consistent. Integers stay Smi. Mixing in one
1.5makes the whole array doubles, and mixing in one string makes it generic. - Avoid creating holes: no gaps when writing, no
deleteon elements, and preferpushor literals overnew Array(n)for small arrays. - Don't read past
length. - Use typed arrays for large numeric data.
- Treat this as tuning for hot code that profiling has pointed to. A holey array in code that runs ten times is not worth rewriting.
Exercise
An array is created as [1, 2, 3], then arr.push(2.5) runs, and then arr.pop() removes the 2.5. What is its elements kind, and why?
Show answer
It is PACKED_DOUBLE_ELEMENTS. Pushing 2.5 moved it from PACKED_SMI_ELEMENTS to the double kind, and elements kind transitions never go back toward a more specific kind, even when the value that caused the change is removed.
Exercise
Why is reading arr[5] from a HOLEY_SMI_ELEMENTS array slower than reading it from a PACKED_SMI_ELEMENTS array, even if index 5 holds a value?
Show answer
The code for holey arrays has to check whether the slot contains the hole marker. If it does, the engine must look up the index on the prototype chain, because JavaScript allows Array.prototype or Object.prototype to supply indexed values. Packed arrays are known to have no holes, so optimized code can skip that check.
Exercise
You need a 1,000,000-element buffer of floating-point samples that a hot loop will update. Compare new Array(1000000).fill(0) with new Float64Array(1000000).
Show answer
new Array(n).fill(0) produces a HOLEY_SMI_ELEMENTS array that stays holey after fill. Writing fractional samples then moves it to HOLEY_DOUBLE_ELEMENTS, so reads keep hole checks and the array went through a transition. Float64Array has a fixed element type of raw 64-bit floats, no holes, and no transitions, so it is the better fit.