This page looks best with JavaScript enabled

Assign values vs. push in Javascript arrays

 ·   ·  ☕ 1 min read

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 -

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
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]
Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things