Assigning [ ] performs better than Array(n) - Reports attached.

Vani Shivanand - Jul 15 '20 - - Dev Community

Here is a small snippet that was measured using jsperf sit

Alt Text

That means Array(n) is a lot slower than [].

What might be the reason?

In the background there are different types of arrays though for a developer it looks like there is only one Array type.

For the sake of scope, two types can be discussed here.

  • Holey element type
  • Packed element type

If we initialize the array with a size, it create an array with Holey element type. Otherwise Packed element type. There are different cases when the javascript engine converts packed element array type into holey.

One of it is a delete operation. Another case is,

const arr = [];
arr[4] = 10;

In the above snippet, though in the first line it creates a packed array. Since there are no elements on index 0,1,2 & 3, the javascript engine converts it into holey array.

That was background. What might be the reason for performance difference?

For a packed array, all that the javascript engine needs to do to find an element is,

  • To check if the index is in the range (zero to arr.length)
  • return value if hasOwnProperty of that index is true (as array is stored in exact object format with index as key)

What if it is a holey array?

  • To check if the index is in the range
  • hasOwnProperty of that index
  • hasOwnProperty of Array.prototype
  • hasOwnProperty of Object.prototype
  • and the same with any/all extended entities

Because in a holey array, the javascript engine can't decide just based on the range (zero to arr.length)

That's the reason, any operation on holey array takes several more steps than packed array causing performance difference.

Reference : https://www.youtube.com/watch?time_continue=445&v=m9cTaYI95Zc&feature=emb_title

Thanks for reading!

. . . . . . . . . . . . .
Terabox Video Player