Array .concat() vs. .push() (v21)

Revision 21 of this benchmark created by rvmn on


Description

"concat strings, then split" was broken - it just added the string "toAdd" instead of the variable toAdd

update: added arr[arr.length] = case (instead of push)

Setup

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
        toAdd = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],arrc=[];

Test runner

Ready to run.

Testing in
TestOps/sec
.push() (with empty array of length == 10)
var arr = new Array(10),
    toAdd = new Array(10);

for (var i = 0, iM = toAdd.length; i < iM; i++) {
 arr.push(toAdd[i]);
}
ready
.push() (array of numbers)
for (var i = 0, iM = toAdd.length; i < iM; i++) {
 arr.push(toAdd[i]);
}
arrc=arr;
ready
concat strings, then split
var arrJ = JSON.stringify(arr).slice(1,-1),
    toAddJ = JSON.stringify(toAdd).slice(1,-1);

var newstr = arrJ + "," + toAddJ;
arrc=newstr.split(",");

 
ready
.concat() (array of numbers)
arrc = arr.concat(toAdd);
ready
.concat() (several arrays of numbers)
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    toAdd = [[1, 2], [3], [4], [5], [6], [7], [8], [9], [10]];


for (var i = 0, iM = toAdd.length; i < iM; i++) {
 arrc = arr.concat(toAdd[i]);
}
ready
.push() w/ .apply()
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    toAdd = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

Array.prototype.push.apply(arr, toAdd);
ready
manual array insertion
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
    toAdd = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

for (var i = 0, iM = toAdd.length, arrLen = arr.length; i < iM; i++) {
 arr[arrLen + i] = toAdd[i];
}
ready

Revisions

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