有效地计算JavaScript中对象的键/属性数 [英] Efficiently counting the number of keys / properties of an Object in JavaScript

查看:58
本文介绍了有效地计算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

v8 objects.cc

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

v8 objects.cc

这篇关于有效地计算JavaScript中对象的键/属性数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆