'for' vs 'for in' loop speed

JavaScript performance comparison

Revision 3 of this test case created by

Preparation code

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script>
  var arr = [];
  for (var i = 0; i < 100000; i++) {
    arr.push(i);
  }
  
  var obj = {};
  for (var i = 0; i < 100000; i++) {
    obj[i] = i;
  }
</script>
    

Preparation code output

Test runner

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

Java applet disabled.

Testing in CCBot 2.0.0 / Other 0.0.0
Test Ops/sec
for loop
var sum = 0;
for (var i = 0; i < arr.length; i++) {
  sum += arr[i];
}
window.sum = sum;
pending…
for in loop
var i, sum = 0;
for (i in arr) {
  sum += arr[i];
}
window.sum = sum;
pending…
for loop 2
var sum = 0;
for (var i = 0, len = arr.length; i < len; i++) {
  sum += arr[i];
}
window.sum = sum;
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.

0 Comments