DEV Community

Discussion on: Javascript Array.push is 945x faster than Array.concat 🤯🤔

Collapse
 
lrpinto profile image
Luisa Pinto

I am sorry, I do not understand what is the big fuss about this... concat() and push() have two different applications and they were not made to compete with each other. You do not need a study to conclude concat() is a slower option. That is very clear by reading the two first lines of the documentation of each method.

developer.mozilla.org/en-US/docs/W...

developer.mozilla.org/en-US/docs/W...

It is important to understand that you use concat() when you are after immutability, for example, when you want to preserve states. One example where immutability is important is when using React - reactjs.org/tutorial/tutorial.html....

Otherwise, you use push when you don't care about changing the arrays (one of them at least).

I am very much more surprised immutability was not mentioned in this article, than with the difference between the performance of each method.

Collapse
 
shiling profile image
Shi Ling • Edited

While that is true, and although it just so happened that in my use case immutability doesn't matter, but it is still worthwhile to consider using other methods to merge arrays instead of concat, while still preserving the source arrays.

If you needed to merge thousands of small arrays in a loop without modifying the source arrays for example, you should create a new result array and use push the source arrays instead to avoid the penalty of copying the first array during each loop when you use concat.

Naive code to merge 1000 arrays with concat (basically what I did, which in my case is 15,000 arrays):

for(var i = 0; i < 1000; i++){
  arr1 = arr1.concat(arr2)   // arr1 gets bigger and bigger, so this gets more expensive over time
}

Faster code to merge 1000 arrays with push w/o modification to source arrays:

let result = []
result.push(...arr1)
for(var i = 0; i < 1000; i++){
  result.push(...arr2) 
}

Also, given by the name, it's not very obvious to people that concat creates a new array instead of modifying the first array. And even though I frequently read MDN docs, I still sometimes forget that concat creates the result as new array.

Collapse
 
johncip profile image
jmc • Edited

it's not very obvious to people that concat creates a new array instead of modifying the first array

I always forget too 😂

Thread Thread
 
joineral32 profile image
Alec Joiner

FWIW, to me it is very intuitive that concat would create a new array since when I hear the word 'concat' I immediately think of strings. Maybe it's misguided, but that leads me to expect other things to behave the same way strings would.