Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript concat vs push benchmark

There is this test on jsperf : http://jsperf.com/javascript-array-concat-vs-push

It shows that concat is faster, but if you get that result in the initial array, without using a third variable, concat is much, much slower :

for (i = 10000; i > 0; i--) {
   arr1 = arr1.concat(arr2);
}

Even if you use a local var, but with the same name, the result is the same :

for (i = 10000; i > 0; i--) {
   var arr1 = arr1.concat(arr2);
}

Can someone explain this ?

like image 799
ovi Avatar asked Oct 20 '25 05:10

ovi


1 Answers

You're mutating the original array in a loop.

for (i = 10000; i > 0; i--) {
   arr1 = arr1.concat(arr2);
}

Here the size of arr1 keeps growing and as the array gets bigger it will get slower because it has to allocate more memory.

for (i = 10000; i > 0; i--) {
   var arr3 = arr1.concat(arr2);
}

Here you are assigning to a new variable without mutating arr1 or arr2 so your testing the performance of concatenating two small arrays.

In the arr1 case your testing the performance of concatenating one large array with a small one.

like image 183
Raynos Avatar answered Oct 22 '25 20:10

Raynos