DEV Community

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

Collapse
 
4mitch profile image
Dima

Seems the problem is not in concat, but in = itself.
As I can see map of concat is even faster than push

console.time('how long');
var arBig = 
[...Array(10000).keys()].map( function(step) {
  return arr1.concat(arr2);
});
console.log(arBig.length);
console.timeEnd('how long');

Plz check jsperf.com/javascript-array-concat...

Collapse
 
merri profile image
Vesa Piittinen

Not comparable: the concat mapper creates 10000 arrays of 20 item arrays, while the other functions create an array of 100010 items.

Collapse
 
4mitch profile image
Dima

Ahh, indeed!
Well, with reduce-concat timing became the same as arr1 = arr1.concat :(

console.time('how long');
var arBig = 
[...Array(10000).keys()].reduce( function(acc, val) {
  return acc.concat(arr2);
}, arr1);
console.log(arBig.length);
console.timeEnd('how long');