concat perf test CORRECT (v9)

Revision 9 of this benchmark created 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 4 testscases of arrays which must be combined.
function makeArrays(i) {
    return [
        range(2,3).map(function(){return range(80,90)}),
        range(8,10).map(function(){return range(50,80)}),
        range(40,45).map(function(){return range(0,80)}),
        range(1000,1100).map(function(){return range(0,5)})
    ];
}
var tests = range(100).map(makeArrays);
realResults = tests.map(function(arrays){return [].concat.apply([], arrays)});

</script>

Teardown


    if (JSON.stringify(results) != JSON.stringify(realResults)) {
        console.log('got: ', results, 'expected: ', realResults);
        throw "This test case "+this+" returns the wrong results. See console."
    }
  

Test runner

Ready to run.

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

return [].concat.apply([], arrays);

})
ready
repeated concat with for loop
results = tests.map(function(arrays){

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

})

// Probably slow because recreating array each time you concat a new array onto the end (javascript has non-functional data structures); a.concat(b) is okay for joining just two arrays together.
ready
arrays.reduce(function(a,b){return a.concat(b)}, [])
results = tests.map(function(arrays){

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

})

// Probably slow because recreating array each time you concat a new array onto the end (javascript has non-functional data structures).
ready
push each array one-by-one: push(#,#,...,#), push(#,#,...,#), ...
results = tests.map(function(arrays){

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

})

// Perhaps slow on some browsers because of the overhead of dealing with O(N) function parameters.
ready
push each element one-by-one: push(#), push(#), ...
results = tests.map(function(arrays){

result = [];
for(var i=0; i<arrays.length; i++) {
    var a = arrays[i];
    for(var j=0; j<a.length; j++)
        result.push(a[j]);
}
return result;

})

// Perhaps slow on some browsers because the inner loop is not native.
ready

Revisions

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