Recently, I had to work on optimising a task that involved the creation of really large arrays (~ 10⁸ elements).
I tested a few different methods, and, according to jsperf, the following option seemed to be the fastest.
var max = 10000000;
var arr = new Array(max);
for (let i = 0; i < max; i++) {
arr[i] = true;
}
Which was ~ 85% faster than
var max = 10000000;
var arr = [];
for (let i = 0; i < max; i++) {
arr.push(true);
}
And indeed, the first snippet was much faster in my actual app as well.
However, my understanding was that the V8 engine was able to perform optimised operations on array with PACKED_SMI_ELEMENTS
elements kind, as opposed to arrays of HOLEY_ELEMENTS
.
So my question is the following:
- if it's true that
new Array(n)
creates an array that's internally marked withHOLEY_ELEMENTS
, (which I believe is true) and - if it's true that
[]
creates an array that's internally marked withPACKED_SMI_ELEMENTS
(which I'm not too sure is true)
why is the first snippet faster than the second one?
Related questions I've been through: