Reputation: 566
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.
Upvotes: 3
Views: 201
Reputation: 6561
Another possibility could have been that push()
is more expensive than assigning to a fixed position. But tests show it is not the case.
What happens is that empty arrays get a relatively small starting capacity (either hash pool or actual array), and increasing that pool is expensive. You can see that by trying with lower sizes: at 100 elements, the performance difference between Array(100)
and []
disappears.
Upvotes: 0
Reputation: 7045
Yes. When you allocate size, interpreter knows that it has allocate only 1000 element memory/space. So, when you insert element, it is just one operation. But when you declare dynamic array, 2nd scenario your case, interpreter has to increase size of the array and then push the element. It is 2 operations!
Upvotes: 0
Reputation: 86
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.
Upvotes: 6