gpt4 book ai didi

javascript - For Loop 和 .hasOwnProperty 哪个更快?

转载 作者:数据小太阳 更新时间:2023-10-29 05:08:07 26 4
gpt4 key购买 nike

我正在做一个项目,我需要从一个巨大的用户数据列表中提取一个被排除的用户列表。这让我想知道在 array 中使用带有排除 id 的双重 for 循环 是否更快。或者,如果将 id 放入对象属性并使用 .hasOwnProperty() 会更快。

var mainList = LARGE JSON OBJECT OF DATA.
var eArray = ["123456","234567","345678","456789","012345"];
var eObject = {"123456":"0","234567":"0","345678":"0","456789":"0","012345":"0"};

使用双重 For 循环 方法:

for(i=0; i < mainList.length; i++){
for(j=0; j < eArray.length; j++){
if(mainList[i]['id'] === eArray[j]){
//Do Something
}
}
}

使用 .hasOwnProperty() 方法:

for(i=0; i < mainList.length; i++){
if(eObject.hasOwnProperty(mainList[i]['id'])){
//Do Something
}
}

我意识到还有其他方法可以使循环更快,例如将长度存储在变量中。我已尝试对此进行简化。

感谢您提供任何信息。

最佳答案

您错过了第三种更快的选择。如果您没有以任何方式修改 Object.prototype,并且 ID 不太可能是原型(prototype)值(如 valueOf 等),您可以简单地像这样使用 for 循环:

for(var i=0; i < mainList.length; i++)
{
if (eObject[mainList[i].id] !== undefined)
{//or typeof eObject[mainList[i].id] !== 'undefined'
//do something
}
}

检查 the updated JSPref ,这是目前最快的方法(57,252,850 ops/sec 对比双循环 17,503,538 ops/sec)

关于javascript - For Loop 和 .hasOwnProperty 哪个更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17648395/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com