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

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 indexes are not have any values
ex — [1,2,,4,5,6]

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 indexes are not having any values
ex — [1,2,,4,5,6]

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….