objdir

JavaScript performance comparison

Revision 15 of this test case created by lauris

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var range = function(min, max, diff) {
      "use strict";
      var returnList = [];
      i = min;
      if (!diff) {
        diff = 1;
      }
      for (; i < max; i = i + diff) {
        returnList.push(i);
      }
      return returnList;
    },
      obj = {},
      data = range(1, 10000),
      i = 0;
    for (; i < data.length; i += 1) {
      obj[i] = i + 1;
    }
};
</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
for (var a in obj) {
  return (a + "->" + obj[a]);
}
pending…
for in cached
var a;
for (a in obj) {
  return (a + "->" + obj[a]);
}
pending…
Object prototype
Object.keys(obj).forEach(function(key) {
  return (key + "->" + obj[key]);
});
pending…
Object prototype with for loop
var keys = Object.keys(obj),
  len = keys.length;
for (; i < len; i += 1) {
  return (keys[i] + "->" + obj[keys[i]]);
}
pending…
for in has own prop
for (var a in obj) {
  if (obj.hasOwnProperty(a)) {
    return (a + "->" + obj[a]);
  }
}
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:

1 comment

Steve Thomson commented :

I'm not sure any of these tests are valid. Running the following in Node exits after the first iteration (as you might expect). The only test that runs all the way is the forEach so no wonder the others are showing as faster!

var a;
var obj = { 'foo': 1, 'bar': 2 };
for (a in obj) {
  return (a + "->" + obj[a]);
}

Add a comment