Counting the properties in an Object

JavaScript performance comparison

Revision 3 of this test case created by Shane Brinkman-Davis Delamore

Preparation code


      
      <script>
Benchmark.prototype.setup = function() {
  function generateObjects(lengths) {
    var objects = []
    for (var i = 0; i < lengths.length; i++) {
      var obj = {};
      var len = lengths[i];
      for (var j = 0;  j < len; j++) {obj[i + "-" + j] = i * len + j; }
      obj.len = len;
      objects.push(obj);
    }
    return objects;
  }
  
  var largeObjects = generateObjects([326, 140, 688, 128, 582, 416, 278, 803, 845]);
  var smallObjects = generateObjects([3, 1, 6, 2, 5, 4, 2, 8, 8]);
  
  function objectLengthCount(object) {
    var length = 0;
    for (var key in object) {++length;}
    return length;
  }
  
  function objectLengthCount1(object) {
    for (var key in object) {return true;}
    return false;
  }
  
  function objectLengthCountHasOwnProperty(object) {
    var length = 0;
    for (var key in object) {
      if (object.hasOwnProperty(key)) ++length;
    }
    return length;
  }
  
  function objectLengthCountHasOwnProperty1(object) {
    for (var key in object) {
      if (object.hasOwnProperty(key)) return true;        
    }
    return false;
  }
  function objectLengthKeys(object) {
    return Object.keys(object).length;
  }

};
</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
largeObjects: Object.keys
for (var i = 0; i < largeObjects.length; i++ ) {
  var len = objectLengthKeys( largeObjects[i] );
}
pending…
largeObjects: counting
for (var i = 0; i < largeObjects.length; i++ ) {
  var len = objectLengthCount( largeObjects[i] );
}
pending…
largeObjects: precomputed
for (var i = 0; i < largeObjects.length; i++ ) {
  var len = largeObjects[i].len;
}
pending…
largeObjects: count to 1
for (var i = 0; i < largeObjects.length; i++ ) {
  var hasKeys = objectLengthCount1( largeObjects[i] );
}
pending…
smallObjects: count to 1
for (var i = 0; i < smallObjects.length; i++ ) {
  var hasKeys = objectLengthCount1( smallObjects[i] );
}
pending…
smallObjects: Object.keys
for (var i = 0; i < smallObjects.length; i++ ) {
  var len = objectLengthKeys( smallObjects[i] );
}
pending…
smallObjects: counting
for (var i = 0; i < smallObjects.length; i++ ) {
  var len = objectLengthCount( smallObjects[i] );
}
pending…
largeObjects: counting with hasOwnProperty
for (var i = 0; i < largeObjects.length; i++ ) {
  var len = objectLengthCountHasOwnProperty( largeObjects[i] );
}
pending…
smallObjects: counting with hasOwnProperty
for (var i = 0; i < smallObjects.length; i++ ) {
  var len = objectLengthCountHasOwnProperty( smallObjects[i] );
}
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