There is this myth that assigning array elements is better performant than push. I believe this originated from Javascript of yore, but is not relevant anymore.
In fact, today push may be almost equal to or edge out assignment of array elements using keys (depending on runtime engine that is).
A quick test
Let us do a really quick test -
- create an array of 1000 elements, assign each element with key
- compare the performance against just
pushing a 1000 elements to a blank array
Code below -
console.time("assign");
const arrA = new Array(1000);
for (let i = 0; i < arrA.length; i++) {
arrA[i] = i;
}
console.timeEnd("assign");
const arrB = [];
console.time("push");
let i = -1;
while (++i < 1000) {
arrB.push(i);
}
console.timeEnd("push");
/* output
assign: 0.342ms
push: 0.128ms
assign: 1.298ms
push: 0.074ms
assign: 0.188ms
push: 0.212ms
assign: 0.216ms
push: 0.079ms
assign: 0.195ms
push: 0.097ms
*/
There is a slight edge to push but nothing that would prevent me from using array keys to assign elements where necessary.
Also see
- [https://jsperf.com/push-method-vs-setting-via-key/3]
- [https://jsperf.com/push-method-vs-setting-via-key/31]