KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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
Tags (comma-separated)
Save Edits
Cancel