Get length of Javascript Object (ie. Associative Array)

Benchmark created by Velizarn on


Preparation HTML

<script src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

Setup

var myArray = new Object();
    myArray["firstname"] = "Gareth";
    myArray["lastname"] = "Simpson";
    myArray["nickname"] = "Ohoboho";
    myArray["age"] = 21;

Test runner

Ready to run.

Testing in
TestOps/sec
jQuery.assocArraySize
jQuery.assocArraySize = function(obj) {
    // http://stackoverflow.com/a/6700/11236
    var size = 0, key;
    for (key in obj) {
        if (obj.hasOwnProperty(key)) size++;
    }
    return size;
};

console.log( jQuery.assocArraySize(Object.keys(myArray)) );
ready
Object.keys().length
console.log(Object.keys(myArray).length+'');
ready
Element count
var element_count = 0;
for (e in myArray) { element_count++; }

console.log( element_count );
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Velizarn on