Array.prototype.push.apply VS adding via loop

JavaScript performance comparison

Revision 3 of this test case created

Preparation code

<script type="text/javascript">
var arr = [];
for (var i = 0; i < 1000; ++i)
        arr.push(i);
</script>
 
<script>
Benchmark.prototype.setup = function() {
    var target = [];
    for (var i = 0; i < 500; ++i)
        target.push(i);
};
</script>

Preparation code output

Test runner

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

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
push
Array.prototype.push.apply(target, arr);
pending…
loop
for (var j = 0, len = arr.length, tlen = target.length; j < len; ++j)
                target[tlen + j] = arr[j];
target.length = tlen + j;
 
pending…
alternative loop
for (var j = 0, len = arr.length, k = target.length; j < len; ++j, ++k)
                target[k] = arr[j];
target.length = k;
pending…
loop length before
var j = 0, len = arr.length, tlen = target.length;
target.length = len + tlen;
for (; j < len; ++j)
                target[tlen + j] = arr[j];
 
pending…
alternative loop length before
var len = arr.length, k = target.length
target.length = len + k;
for (var j = 0; j < len; ++j, ++k)
                target[k] = arr[j];
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:

0 comments

Add a comment