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 ?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With