index vs push

JavaScript performance comparison

Test case created by Mike McCaughan

Info

See if push and index are really as far apart as is rumored (namely, Google says in their JavaScript Style Guide that, "Note that since assigning values to an array is faster than using push() you should use assignment where possible". However, I'm finding the opposite in these tests...

http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml

Preparation code

<script>
  var arr = [], i = 0;
</script>
<script>
Benchmark.prototype.teardown = function() {
    arr = [], i = 0;
};
</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
Index
if (i < 10000000) {
arr[i++] = 'boo';
}
pending…
Push
if (i < 10000000) {
arr.push('boo');
}
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:

1 comment

Mike McCaughan (revision owner) commented :

Doesn't even work in IE9; throws an Out of memory error. Sweet.

Add a comment