for-loop vs. for-in-loop

JavaScript performance comparison

Test case created by Kyle Simpson

Preparation code

<script>
  // setup `arr` array ('small')
  var arr = ['1', true, false, "", void 0, null, 2, 18.5936];
  
  // testing for having deleted keys in array
  delete(arr[3]);
  
  // seed `arr_keys` hash
  var arr_keys = {};
  for (var i = 0; i < arr.length; i++) {
   arr.hasOwnProperty(i) && (arr_keys[i] = 0);
  }
  
  // setup `arr2` array ('medium')
  var arr2 = arr.slice(0);
  for (var j = 0; j < 500; j++) {
   arr2.push(Math.round(Math.random()));
  }
  
  // seed `arr2_keys` hash
  var arr2_keys = {};
  for (j = 0; j < arr2.length; j++) {
   arr2.hasOwnProperty(j) && (arr2_keys[j] = 0);
  }
  
  // setup `arr3` array ('big')
  var arr3 = arr2.slice(0);
  for (var m = 0; m < 5000; m++) {
   arr3.push(Math.round(Math.random()));
  }
  
  // seed `arr3_keys` hash
  var arr3_keys = {};
  for (m = 0; m < arr3.length; m++) {
   arr3.hasOwnProperty(m) && (arr3_keys[m] = 0);
  }
</script>
    

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
big array: for-in-loop on keys
for (var m in arr3_keys) {
 arr3[m];
}
pending…
small array: for-loop
for (var i = 0, len = arr.length; i < len; i++) {
 arr[i];
}
pending…
small array: for-in-loop on keys
for (var i in arr_keys) {
 arr[i];
}
pending…
medium array: for-loop
for (var j = 0, len = arr2.length; j < len; j++) {
 arr2[j];
}
pending…
medium array: for-in-loop on keys
for (var j in arr2_keys) {
 arr2[j];
}
pending…
big array: for-loop
for (var m = 0, len = arr3.length; m < len; m++) {
 arr3[m];
}
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