Array extending: push vs concat

JavaScript performance comparison

Test case created by Jon

Info

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 code

<script>
/**
 * extend an array with another array. See http://stackoverflow.com/a/1374131/1280629
 **/

Array.prototype.extend = function(array) {
    this.push.apply(this, array)
}

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

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

var short_array = []
short_array.length = 5000;

var long_array = []
long_array.length = 150000;
</script>
<script>
Benchmark.prototype.setup = function() {
    var array_to_extend = [];
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
Extend via push apply - short array
array_to_extend.extend(short_array);
pending…
Extend via push for loop - short array
array_to_extend.extend_for_loop(short_array);
pending…
Extend via push for loop (with pre-lengthening of dest array)- short array
array_to_extend.pre_extend_for_loop(short_array);
pending…
Extend via push apply - long array
array_to_extend.extend(long_array);
pending…
Extend via push for loop - long array
array_to_extend.extend_for_loop(long_array);
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

2 comments

Jonathan Quimbly commented :

Where is the array.concat() benchmark?

Jesús Leganés Combarro commented :

I've added array.concat() on the revision 13. By the way: it's the worst alternative by far.

Add a comment