for-in loop vs index look-up

JavaScript performance comparison

Test case created by jan

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var dict = {};
    var indices = [];
    var index;
   
    for (var i = 0; i < 1000; i++) {
      index = 'a' + i;
      dict[index] = i + i;
      indices[i] = index;
    }
};
</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-in
var sum = 0;

for (var i in dict) {
  if (dict.hasOwnProperty(i)) {
    sum += dict[i];
  }
}

return sum;
pending…
index-lookup
var sum = 0;

for (var i in indices) {
  sum += dict[i];
}

return sum;
pending…

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

Compare results of other browsers

0 comments

Add a comment