Skip to content

Memory Layout

Understanding how JavaScript engines store data in memory helps you write more performant code.

Memory AreaStoresSpeedSize
StackPrimitives, references, function framesFastSmall (~1MB)
HeapObjects, arrays, closuresSlowerLarge
// Object in memory (simplified)
const obj = { x: 5, y: 10 };
// Memory (conceptual):
// [Map pointer] → Hidden class (shape)
// [x: 5]
// [y: 10]
// [Property array] → Dynamic properties (if needed)

V8 uses pointer compression (32-bit pointers instead of 64-bit) to save memory:

Without compression: Each pointer = 8 bytes
With compression: Each pointer = 4 bytes ← 50% savings!

V8 tracks array element types for optimization:

[1, 2, 3]; // PACKED_SMI_ELEMENTS (fastest)
[1, 2, true]; // PACKED_DOUBLE_ELEMENTS
[1, 2, 'hello']; // PACKED_ELEMENTS
[1, , 3]; // HOLEY_ELEMENTS (holes = slower)
  • Stack: fast, small, for primitives and references
  • Heap: slower, large, for objects
  • Pointer compression saves ~40% memory
  • Elements kinds affect array performance
  • Avoid holes in arrays for best performance