for-in versus Object.keys(..) for loop

JavaScript performance comparison

Revision 5 of this test case created

Info

Testing if the perf hit for a for loop over Object.keys(..) is enough to matter as compared to for-in.

Preparation code

<script>
// pre-ES5 polyfill for Object.keys()
Object.keys=Object.keys||function(o,k,r){r=[];for(k in o)r.hasOwnProperty.call(o,k)&&r.push(k);return r}

function iterate1() {
   var v = "", i = 0;
   for (i in obj) {
      v = obj[i];
   }
}

function iterate2() {
   var v = "", i = 0, ks = Object.keys(obj);
   for(var i = 0, len = ks.length; i < len; ++i)
      v = obj[ks[i]];
}

var obj = {}, j = 0;
while(j < 5000) {
  obj[j.toString()] = j.toString();
  ++j;
}
</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
iterate1();
pending…
Object.keys(..) for loop
iterate2();
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