0

I was curious (and had nothing to do) and decided to run a benchmark with the following for adding items to arrays:

var num = [];
for (var i = 0; i < 1000; i++) {
  num.push(i);
}

seems to be 90% slower than

var num = [];
for (var i = 0; i < 1000; i++) {
  num[i] = i;
}

The positions of the items do not matter to me in this case (as long as they are added to the array).
Can anyone explain why Array.prototype.push() is so much slower? You can find the benchmark here.

Capt 171
  • 625
  • 3
  • 14
  • 1
    Have you seen [Why push method is significantly slower than putting values via array indices in Javascript](/q/21034662/4642212), all the linked posts, and everything else found on [Google](//google.com/search?q=site:stackoverflow.com+js+push+slow)? – Sebastian Simon Oct 16 '21 at 12:21

0 Answers0