1

How to get number of properties in an Object without the performance penalty that is associated with Object.keys().length?

13

3 Answers 3

3

You could do a for-in loop, it's pretty fast. Basically it iterates through all the keys in the object and increments the counter for each one. Based on a quick benchmark in my console, it's about 5 times faster than Object.keys().length

var counter = 0;
for(var i in obj){
  counter++;
}
Sign up to request clarification or add additional context in comments.

Comments

1

If you want a fast approach, basically you have two possibilities:

  • Keep track of the size of your object manually. Store the size in a variable, increase it when creating a property, and decrease it when deleting.

    var myObj = {},
        size = 0;
    myObj.foo = 1; ++size;
    myObj.bar = 2; ++size;
    size; // 2
    
  • Use a similar data structure which exposes the size. For example, ES6 maps.

    var myMap = new Map();
    myMap.set("foo", 1);
    myMap.set("bar", 2);
    myMap.size; // 2
    

11 Comments

in that code, it seems using Map() isn't actually any faster than using a plain object and running Object.keys(). i realize it's a stub, but would you expect Map to be faster on a larger collection?
@dandavis I don't only expect it. It must be faster. Map operations are required to be sublinear (on average) with the size of the map, Object.keys is linear (unless it has been cached or something).
@Oriel: why do these result seemingly contradict what you say "must be faster": pagedemos.com/84xj3qxfm7cz/2 ? i ran them a bunch and i never saw a Map outperform an Object... i trust you (a lot), but i like to verify ;)
@dandavis I think the test should be more like this. Map: 0.1, Obj: 2150. The advantage of maps is noticeable when the size is huge.
Object.keys should be taking longer as according to the spec size is a getter that loops the List entries and returning a count. Object.keys however does two loops: one in EnumerableOwnNames and then one in CreateArrayFromList of course speed also depends on the vendors implementation
|
0

You can switch to Map, which is similar to Object, but also you can get size of it, and iterate through keys. It is supported by many browsers, and for older ones there are polyfills.

1 Comment

While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.