8

我正在做一个项目,我需要从庞大的用户数据列表中提取被排除用户的列表。这让我想知道for looparray. 或者,如果将 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 Loop方法:

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
    }
}

我意识到还有其他方法可以使循环更快,例如将长度存储在变量中。我试图简化这一点。

感谢您提供任何信息。

4

4 回答 4

6

.hasOwnProperty()如果您考虑一下,这种方法会更快是有道理的,因为它只使用 1 for loop

错误的

我其实有点惊讶。我期待双循环会更慢。但我想你不能低估 a 的速度for loop

双环

虽然这对我来说似乎是最慢的,但这实际上是最快的板凳7,291,083 ops/sec

.hasOwnProperty()

我可以看到这会如何变慢,因为函数比语句慢。这长椅在1,730,588 ops/sec

如果..在

@Geuis 的答案包括 if..in 语句,并认为我会测试看起来最快的速度,但2,715,091 ops/sec它仍然无法击败 for 循环。

结论

for 循环很快。双循环的运行速度比使用条件快4 倍以上.hasOwnProperty(),几乎比使用条件快3 倍if..in。但是,性能并不是很明显;速度真的很重要,以至于您需要使事情复杂化。在我看来,if..in方法是要走的路。

在您的浏览器中自行测试。我正在使用Google Chrome 28.

更新

请务必注意,使用for..in声明将为您提供最佳性能。

于 2013-07-15T07:07:16.343 回答
6

您错过了第三种更快的选择。如果您没有Object.prototype以任何方式修改过,并且 ID 不太可能是原型值(类似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
    }
}

检查更新的 JSPref ,这是迄今为止最快的方法(57,252,850 ops/sec vs 17,503,538 ops/sec for the double loop)

于 2013-07-15T07:21:14.887 回答
1

Edit to show the proper code for future internet traversers: Visit http://jsperf.com/stackoverflow-for-vs-hasownproperty/5 for the comparison

var testVal = 'BigBrownFox',
    arr = [1,4,'asd','BigBrownFox',9];

if( arr.indexOf('testVal') > -1 ){
    //do something
}

For testing an array of values for existence in another array:

var testVal = ['BigBrownFox'],
    arr = [1,4,'asd','BigBrownFox',9];

for(var i=0, len=testVal.length; i<len; i++){

    if( arr.indexOf(testVal[i]) > -1 ){
        //do something
    }

}

Actually, your approach in both cases is slightly off.

If are using an array, just use the indexOf function. If the testing value exists, it will return its index. Otherwise it's -1 if not found. No loop is needed at all.

In the case of an object, you don't use .hasOwnProperty. Yeah, it does what you want but its overcomplicated and slower because you're doing a function call.

Just use

var eObject = {"123456":"0","234567":"0","345678":"0","456789":"0","012345":"0"};
if( '234567' in eObject ){ //do something }

Hope this helps.

于 2013-07-15T07:11:54.273 回答
0

在 chrome 中,最快的循环是

在较旧的/其他浏览器中,最快的是 while-- 循环。

特别是如果您缓存长度。(如果 mainList 很大,则非常重要)

我看到你在 eObject 中只有字符串我也建议使用(eObject[mainList[i].id])

这比(eObject[mainList[i].id] !== undefined)

var i=mainList.length;
while(i--){
  if (eObject[mainList[i].id]) {
    //do something
  }
}
于 2013-07-15T08:47:04.960 回答