Array extending: push vs concat (v24)

Revision 24 of this benchmark created on


Description

Compares techniques for extending an array with another array.

See http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array

Preparation HTML

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
/**
 * extend an array with another array. See http://stackoverflow.com/a/1374131/1280629
 **/
Array.prototype.extend_push_apply = function(array) {
    this.push.apply(this, array)
}

Array.prototype.extend_concat = function(array) {
    this.concat(array)
}

Array.prototype.extend_for_loop = function(array) {
    for (var i = 0; i < array.length; ++i) {
        this.push(array[i]);
    };    
}

Array.prototype.extend_for_index = function(array) {
    var j = this.length;
    this.length += array.length;
    for (var i = 0; i < array.length; ++i) {
        this[j++] = array[i];
    }
}

Array.prototype.extend_forEach = function (array) {
    array.forEach(function(x) {this.push(x)}, this);    
}

Array.prototype.extend_splice = function (array) {
    array.unshift(array.length)
    array.unshift(this.length)
    Array.prototype.splice.apply(this,array) 
    array.shift() // restore b
    array.shift() //
}

Array.prototype.extend_jquery_merge = function (array) {
    $.merge(this, array);
}

var short_array = [];
var length = 10000;
while(length--){
   short_array.push(Math.random()*3000);
}
</script>

Setup

var array_to_extend = [];

Test runner

Ready to run.

Testing in
TestOps/sec
Extend via push apply
array_to_extend.extend_push_apply(short_array);
ready
Extend via splice
array_to_extend.extend_splice(short_array);
ready
Extend via push for loop
array_to_extend.extend_for_loop(short_array);
ready
Extend via push forEach
array_to_extend.extend_forEach(short_array);
ready
Extend via index for loop
array_to_extend.extend_for_index(short_array);
ready
Extend via jQuery Merge
array_to_extend.extend_jquery_merge(short_array);
ready

Revisions

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