DEV Community

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

Collapse
 
neolivz profile image
Jishnu Viswanath

I modified the code

var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
var arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
var arr3 = []

var date = Date.now();
for (let i = 10000; i > 0; i--) {
  var arr  =[];
  Array.prototype.push.apply(arr, arr1);
  Array.prototype.push.apply(arr, arr2);
  arr1 = arr;
}

Date.now() - date;

This gives the exact same performance as the concat function, basically creating the new object is the one which is costing the extra perf.
I mean concat function, actually creates a new array and append existing array into that, that is costly affair considering that it will constantly increase 10, 20, 30,40.... 99990entries in it and append in hte next iteration