Javascript array concat vs push (v17)

Revision 17 of this benchmark created by Austin Appleby on


Description

1) var arr1=[1,2,3]; var arr2=[4,5,6]; var arr3=arr1.concat(arr2);

2) var arr1=[1,2,3]; var arr2=[4,5,6]; Array.prototype.push.apply(arr1,arr2);

Setup

var arr1 = [];
    var arr2 = [];
    var arr3 = [];
    
    for (var i = 0; i < 1000; i++) {
      arr1[i] = Math.sin(i);
      arr2[i] = Math.cos(i);
    }

Test runner

Ready to run.

Testing in
TestOps/sec
concat whole array
for (i = 100; i > 0; i--) {
  arr3 = arr1.concat(arr2);
}
ready
push each element
for (i = 100; i > 0; i--) {
  arr3 = [];
  for (var j = 0; j < arr1.length; j++) arr3.push(arr1[j]);
  for (var j = 0; j < arr2.length; j++) arr3.push(arr2[j]);
}
ready
manual concat
for (i = 100; i > 0; i--) {
  var l1 = arr1.length;
  var l2 = arr2.length;
  arr3 = new Array(l1 + l2);
  for (var j = 0; j < arr1.length; j++) arr3[j] = arr1[j];
  for (var j = 0; j < arr2.length; j++) arr3[l1 + j] = arr2[j];
}
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.