有效地计算JavaScript中对象的键/属性数 [英] Efficiently counting the number of keys / properties of an Object in JavaScript
问题描述
此问题与恒定时间"方式?我最关心的是在Node.JS中执行此操作,因为浏览器上的大多数对象都不太大,因此值得关注.
看来Object.keys(obj).length
在Google Chrome和Node.JS中以线性时间O(n)返回(即取决于obj
中的键数).是否有更好的O(1)方法?
我在Node.JS中做了一些测试(来源在下面)
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]);
}
对于n = 10e3、10e4、10e5、10e6 ...结果是:
test10000: 5ms
test100000: 20ms
test1000000: 371ms
test10000000: 4009ms
查看源代码,尤其是GetLocalElementKeys
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
See the source, specifically GetLocalElementKeys
这篇关于有效地计算JavaScript中对象的键/属性数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!