How to get number of properties in an Object without the performance penalty that is associated with Object.keys().length?
3 Answers
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; // 2Use 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
dandavis
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?Oriol
@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).dandavis
@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 ;)
Patrick Evans
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
|
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
Joe Thomas
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
Object.keysis very fast anywayJSON.stringify()to count properties?