DEV Community

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

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.