This question is almost identical to How to efficiently count the number of keys/properties of an object in JavaScript?.
I want to know one extra piece of information: what is a "constant-time" way of determining the number of keys in an Object? I am mostly concerned with doing this in Node.JS, as most Objects on the browser aren't too large to be of great concern.
EDIT:
It appears that Object.keys(obj).length
returns in linear time O(n) in Google Chrome and in Node.JS (i.e. dependent on the number of keys in obj
). Is there a better O(1) method?
I did some testing in Node.JS (source is below)
var tests = [10e3, 10e4, 10e5, 10e6]
for(j in tests) {
var obj = {};
for(i = 0; i < tests[j]; i++)
obj[i] = i;
console.time('test' + tests[j]);
Object.keys(obj).length;
console.timeEnd('test' + tests[j]);
}
For n = 10e3, 10e4, 10e5, 10e6... results are:
test10000: 5ms
test100000: 20ms
test1000000: 371ms
test10000000: 4009ms
3 Answers 3
After a bit of research, there is no way to determine the number of keys in a JavaScript Object in constant time, at least not in Node... and not quite yet. Node internally keeps track of this information, but it does not expose it, since there is no method to do so in ECMA-262 5th.
It's worth noting that Harmony (ECMA version 6) may natively support Maps and Sets. Not sure what the spec for these will turn out to be.
I am told that we need to bring this up with TC39 committee.
Bug report for V8: http://code.google.com/p/v8/issues/detail?id=1800
ECMA 6 harmony introduces Map
and Set
classes which you can probably utilize (in the future :)
var map = new Map;
map.set('a', 'b');
console.log(map.size); // prints 1
I believe it should have complexity O(1), not tried though. You can run it in node 0.11+ via node --harmony script.js
.
Another way is to use Proxy
class which also has been added in harmony.
See the source, specifically GetLocalElementKeys
-
I'm too lazy to do this. English, please. I'd gladly accept your answer. :PBMiner– BMiner10/31/2011 16:56:53Commented Oct 31, 2011 at 16:56
-
Depending on what the object contains they do different things, worst case seems to be doing 1 for loop through all the elements.Andrew– Andrew10/31/2011 17:23:24Commented Oct 31, 2011 at 17:23
Explore related questions
See similar questions with these tags.
Object.keys(o).length
is O(n)..length
on an array is O(1).