Object.keys ForEach vs for-in hasOwnProperty with cached length and while loop increment and decrement

JavaScript performance comparison

Revision 8 of this test case created by

Preparation code

<script>
// Declaring our Animal object
var Animal = function () {

    this.name = 'unknown';

    this.getName = function () {
        return this.name;
    }

    return this;
};

// Declaring our Dog object
var Dog = function () {

    // A private variable here        
    var private = 42;

    // overriding the name
    this.name = "Bello";

    // Implementing ".bark()"
    this.bark = function () {
        return 'MEOW';
    }  

    return this;
};


// Dog extends animal
Dog.prototype = new Animal();

// Creating an instance of Dog.
var obj = new Dog();

function iterateA() {
  var ret = "";
    
  for (var prop in obj) {
    if( obj.hasOwnProperty( prop ) ) {
      ret += obj[prop];
    } 
  }
    
  return ret;
}

function iterateB() {
  var ret = "";
    
  Object.keys(obj).forEach(function (prop) {
    ret += obj[prop];
  });

  return ret;
}

function iterateC() {
   var ret = "";

   for (var i = 0, keys = Object.keys(obj), len = keys.length; i < len; i++) {
       ret += obj[i];
   }

   return ret;
}

function iterateD() {
   var ret = "";
   var i = -1, keys = Object.keys(obj), len = keys.length;

   while(++i < len) {
       ret += obj[i];
   }

   return ret;
}

function iterateE() {
   var ret = "";
   var keys = Object.keys(obj), i = keys.length;

   while(--i) {
       ret += obj[i];
   }

   return ret;
}

var tmp;
</script>
      
<script>
Benchmark.prototype.setup = function() {
  tmp = "";

};
</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
for-in
tmp += iterateA();
pending…
Object.keys forEach
tmp += iterateB();
pending…
for-in Object.keys
tmp += iterateC();
pending…
while loop increment
tmp += iterateD();
pending…
while loop decrement
tmp += iterateE();
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