Counting the properties in an Object

JavaScript performance comparison

Test case created by Michael Geary

Info

Ways of counting the number of properties in an object

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 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;
        }
        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 unknown unknown
Test Ops/sec
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. Here’s a list of current revisions for this page:

0 comments

Add a comment