concat perf test CORRECT (v3)

Revision 3 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 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);
var realSolutions = tests.map(function(arrays){return [].concat.apply([], arrays)});

</script>

Teardown


    if (JSON.stringify(results) != JSON.stringify(realSolutions)) {
        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);
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; a++)
        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.