Interesting internals of array in javascript

Interesting  internals of array in javascript

Arrays are a fundamental data structure in JavaScript. Behind the scenes, V8 - Google's JavaScript engine - optimizes arrays in two main ways:

  1. Contiguous arrays

  2. Holey arrays

Contiguous Arrays

For arrays that are densely populated with no undefined elements, V8 uses a contiguous array representation. This means the elements are stored in consecutive memory locations.

This provides several benefits:

  • Faster access - Since elements are contiguous, accessing an element by index is fast.

  • Cache friendliness - Contiguous elements are more cache friendly since they are loaded into the CPU cache together.

  • Memory efficiency - No space is wasted storing undefined values.

V8 uses this representation when:

  • All elements are initialized

  • There are no undefined elements

For example:

  const arr = [1, 2, 3, 4];

This array will be stored as a contiguous array

Contagious Array is further divided into different types based on what data is and where it is in the array.

  • PACKED SMI (SMALL INT)

      const array=[1,2,3,4]
    
  • PACKED DOUBLE(double,float,string)

      const array=[1,2,3,4,6.0,]
    
  • PACKED ELEMENTS

      const array=[1,2,3,4,6.0,'a']
    

    PACKED_SMI >>> PACKED_DOUBLE >> PACKED_ELEMENTS

Holey Arrays

When an array contains undefined elements, V8 uses a holey array representation. This means:

  • Elements are not necessarily stored contiguously

  • undefined elements are represented by "holes" in the array

This allows V8 to:

  • Only allocate memory for initialized elements

  • Still provide O(1) access by index

For example:

  const arr = [1, <3 empty items>, 3];

This array will be stored as a holey array, with the undefined element represented as a hole.

When accessing elements by index, V8 must check for holes and return undefined appropriately. This makes accessing elements slightly slower than in contiguous arrays.

HOLES ARE VERY VERY EXPENSIVE IN JS

Holey array is categorised in further types as

  • HOLEY SMI (SMALL INT)

      const array=[1,2,3,<1 empty value>,4]
    
  • HOLEY DOUBLE(double,float,string)

      const array=[1,2,3,<1 empty value>,4,6.0,]
    
  • HOLEY ELEMENTS

      const array=[1,2,3,<1 empty value>,4,6.0,'a']
    

    HOLEY_SMI >>> HOLEY_DOUBLE >> HOLEY_ELEMENTS

Optimization

V8 continuously monitors arrays as they are used in a program. As arrays transition from holey to contiguous, V8 can optimize the representation.

It is always suggested to use inbuilt javascript methods like .map, .filter, etc as they are optimized by the JS engine , in a lot better way than we can ever manually .