The standard Object implementation (ES5.1 Object Internal Properties and Methods) does not require an Object
to track its number of keys/properties, so there should be no standard way to determine the size of an Object
without explicitly or implicitly iterating over its keys.
So here are the most commonly used alternatives:
1. ECMAScript's Object.keys()
Object.keys(obj).length;
Works by internally iterating over the keys to compute a temporary array and returns its length.
- Pros - Readable and clean syntax. No library or custom code required except a shim if native support is unavailable
- Cons - Memory overhead due to the creation of the array.
2. Library-based solutions
Many library-based examples elsewhere in this topic are useful idioms in the context of their library. From a performance viewpoint, however, there is nothing to gain compared to a perfect no-library code since all those library methods actually encapsulate either a for-loop or ES5 Object.keys
(native or shimmed).
3. Optimizing a for-loop
The slowest part of such a for-loop is generally the .hasOwnProperty()
call, because of the function call overhead. So when I just want the number of entries of a JSON object, I just skip the .hasOwnProperty()
call if I know that no code did nor will extend Object.prototype
.
Otherwise, your code could be very slightly optimized by making k
local (var k
) and by using prefix-increment operator (++count
) instead of postfix.
var count = 0;
for (var k in myobj) if (myobj.hasOwnProperty(k)) ++count;
Another idea relies on caching the hasOwnProperty
method:
var hasOwn = Object.prototype.hasOwnProperty;
var count = 0;
for (var k in myobj) if (hasOwn.call(myobj, k)) ++count;
Whether this is faster or not on a given environment is a question of benchmarking. Very limited performance gain can be expected anyway.