multiple loop comparisons

JavaScript performance comparison

Test case created by Joel Leclerc

Info

Comparison of different loop types

Preparation code

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
Benchmark.prototype.setup = function() {
    var foo = [];
    for (var i = 0; i < 10000; i++) {
      foo[i] = i;
    }
    var counter = 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
for
for (var i = 0; i < foo.length; i++) {
  counter += foo[i];
}
pending…
for...in
for (var i in foo) {
  counter += foo[i];
}
pending…
while
var i = foo.length;
while (--i >= 0) {
  counter += foo[i];
}
pending…
reverse for
for (var i = foo.length - 1; i >= 0; i--) {
  counter += foo[i];
}
pending…
cached for
var l = foo.length;
for (var i = 0; i < l; i++) {
  counter += foo[i];
}
pending…
Object.keys, for...in
var k = Object.keys(foo);
for (var i in k) {
  counter += foo[k[i]];
}
pending…
Object.keys
var k = Object.keys(foo);
for (var i = 0; i < k.length; i++) {
  counter += foo[k[i]];
}
pending…
Object.keys, cached
var k = Object.keys(foo);
var len = k.length;
for (var i = 0; i < len; i++) {
  counter += foo[k[i]];
}
pending…
$.each, key
$.each(foo, function(k) {
  counter += foo[k];
});
pending…
$.each
$.each(foo, function() {
  counter += this;
});
pending…
$.each, key, value
$.each(foo, function(k, v) {
  counter += v;
});
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