Arrays — Implementation in JavaScript/(PACKED &&HOLEY Array)

Anil Verma
2 min readOct 26, 2023

--

Internal Optimisation of Javascript on Arrays

Every JS engine has its own implementation for arrays and with each type of Array javascript performs different kind of optimisation internally.
in this article we are going to see how V8 engine executes these array types internally.

Internal types of JS arrays

Packed Array —
Array with Continuous values(array with values on each index)
ex — [1,2,3,4,5,6]

Holey Array —

Array where some index are not having any values
ex — [1,2,,4,5,6]

Packed Array && Holey Array —

Both have further subcategory based on Elements present in array

  1. SMI ELEMENTS. — If Array Having Integer Values on each index
    ex- Packed Array — [1,2,3,4,5] , Holey Array — [1,2,,4,5]
  2. DOUBLE_ELEMENTS- If Array vaving float Values also in array
    ex- Packed Array — [1,2,6.0], Holey Array — [1,,6.0]
  3. PACKED_ELEMENTS — If Array Having all kinds of Valuesalso in array
    ex- Packed Array — [1,2,6.0, ‘hello’], Holey Array — [1,,6.0, ‘hello’]

Optimisation on Packed Array && Holey Array

Note

  1. Optimisation on Packed array is most effective
  2. Optimisation on Holey array is most costly

Reason
If elements are present on each index(packed) then whenever we look for that elements it get’s returned with that value
const arr = [1,2,3,4,5], arr[1] =2

But there is problem with Holey Array

The difference between Undefined and Empty Array slots

let Hello = new Array(2);  // Two holes
Hello[0] = undefined;
console.log(Hello);
// [undefined, empty]
console.log(Hello[0]); // undefined
console.log(Hello[1]); // undefined

Now, How to know that index is empty or undefined because comparing to undefined does not work —( see above ex.)

🚨 for — console.log(Hello[1])
The V8 engine has to perform a series of operations in order to execute a statement(console.log(Hello[1])).
This results in a declined performance of the Javascript code. for checking the value of Hello[1], the V8 engine performs several checks based on prototype chain for deciding upon the value of Hello[1].

for  -- Hello[1]. -->
check -- bound check Hello.length ---> true
check hasOwnProperty(Array.prototype, '1')
check hasOwnProperty(Object.prototype, '1')
return false

Happy Learning….

--

--

Anil Verma
Anil Verma

Written by Anil Verma

Hi there 👋, I am Anil Verma, a full stack web developer, and JavaScript enthusiast. 👥 Ask me anything about web development. web- https://anilvermaspeaks.in/