Counting the properties in an Object

JavaScript performance comparison

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

Preparation code

<script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/1.2.1/lodash.min.js"></script>

<script src="http://underscorejs.org/underscore-min.js"></script>

<script>
    var _u = _.noConflict();
</script>

      
<script>
Benchmark.prototype.setup = function() {
  // Create a list of objects of various lengths generated with:
  //		for( var i = 1;  i < 10; i++ ) {
  //			console.log( Math.floor( Math.random() * 1000 ) );
  //		}
  
  var lengths = [ 326, 140, 688, 20, 582, 416, 278, 803, 845 ];
  // var lengths = [ 3, 1, 6, 2, 5, 4, 2, 8, 8 ];
  var objects = [];
  for( var iObject = 0;  iObject < lengths.length;  iObject++ ) {
  	var obj = {};
  	var len = lengths[iObject];
  	for( var iProp = 0;  iProp < len;  iProp++ ) {
  		var prop = [ 'z', iObject, iProp ].join('|');
  		obj[prop] = 'z' + prop;
  	}
    obj.len = len;
  	objects.push( obj );
  }
  
  function ObjectLengthCount( object ) {
      var length = 0;
      for( var key in object ) {
          if( object.hasOwnProperty(key) ) {
              ++length;
          }
      }
      return length;
  }
  
  function ObjectLengthModern( object ) {
      return Object.keys(object).length;
  }
  
  var ObjectLengthEither =
      Object.keys ? ObjectLengthModern : ObjectLengthCount;
  

};

Benchmark.prototype.teardown = function() {
  objects = [];

};
</script>

Preparation code output

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
Precomputed
for( var i = 0;  i < objects.length;  i++ ) {
    var len = objects[i].len;
}
pending…
Object.keys(object).length
for( var i = 0;  i < objects.length;  i++ ) {
    var len = ObjectLengthModern( objects[i] );
}
pending…
Counting in a loop
for( var i = 0;  i < objects.length;  i++ ) {
    var len = ObjectLengthCount( objects[i] );
}
pending…
Lo-Dash _.keys(object).length
for( var i = 0;  i < objects.length;  i++ ) {
    var len = _.keys( objects[i] ).length;
}
pending…
Underscore _.keys(object).length
for( var i = 0;  i < objects.length;  i++ ) {
    var len = _u.keys( objects[i] ).length;
}
pending…
Counting or Modern
for( var i = 0;  i < objects.length;  i++ ) {
    var len = ObjectLengthEither( objects[i] );
}
pending…
Lo-Dash _.size(object)
for( var i = 0;  i < objects.length;  i++ ) {
    var len = _.size( objects[i] );
}
pending…
Underscore _.size(object)
for( var i = 0;  i < objects.length;  i++ ) {
    var len = _u.size( objects[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