Search code examples
javascriptarraysperformancev8jsperf

Why iterate by array with size faster


In first example I created empty array of length 1000:

var arr = new Array(1000);

for (var i = 0; i < arr.length; i++)
  arr[i] = i;

In second example created empty array of length 0:

var arr = [];

for (var i = 0; i < 1000; i++)
  arr.push(i);

Testing in Chrome 41.0.2272.118 on OS X 10.10.3 and first block run faster. Why? Because JavaScript-engine knows about array size?

Benchmark is here http://jsperf.com/poerttest/2.


Solution

  • If you don't specify the array size it will have to keep allocating more space. But if you specify the size at the beginning, it only allocates once.