concat perf test CORRECT (v11)

Revision 11 of this benchmark created by Sebastian Markbåge on


Preparation HTML

<script>

function randInt(n) {
    // return random int in range [0,n)
    return Math.floor(Math.random()*n)
}
function range(a,b) {
    // > range(2,5)
    // [2, 3, 4]
    if (b===undefined) {
        b=a; a=0;
    }
    return a==b ? [] : range(a,b-1).concat(b-1);
}

// Make 15 testscases. Each testcase has between 3-8 arrays of length 0-100 which must be combined.
function makeArrays() {
    return range(3+randInt(5)).map(function(){return range(randInt(100))})
}
var tests = range(15).map(makeArrays);

</script>

Test runner

Ready to run.

Testing in
TestOps/sec
[].concat.apply([], arrays)
tests.forEach(function(arrays){

result = [].concat.apply([], arrays);

})
ready
repeated concat with for loop
tests.forEach(function(arrays){

result = [];
for(var i=0; i<arrays.length; i++)
    result = result.concat(arrays[i]);

})
ready
arrays.reduce(function(a,b){return a.concat(b)}, [])
tests.forEach(function(arrays){

result = arrays.reduce(function(a,b){return a.concat(b)}, [])

})
ready
repeated push(#,#,...,#) with for loop
tests.forEach(function(arrays){

result = [];
for(var i=0; i<arrays.length; i++)
    result.push.apply(result, arrays);

})
ready
preallocation
tests.forEach(function(arrays){

var totalLength = 0;
for(var i=0, k = arrays.length; i<k; i++) {
  totalLength += arrays[i].length;
}

var result = Array(totalLength);
var c = 0;
for(var i=0, k=arrays.length; i<k; i++) {
  var subarr = arrays[i];
  for(var j=0,l=subarr.length; j<l; j++) {
    result[c++] = subarr[j];
  }
}

})
ready

Revisions

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