Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Cocoa 为什么for-each比for-loop快?_Cocoa_For Loop - Fatal编程技术网

Cocoa 为什么for-each比for-loop快?

Cocoa 为什么for-each比for-loop快?,cocoa,for-loop,Cocoa,For Loop,我的应用程序以两种方式读取所有联系人: for循环: CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent (); long count = macContact.addressBook.people.count; for(int i=0;i<count;++i){ ABPerson *person = [macContact.addressBook.people objectAtIndex:i];

我的应用程序以两种方式读取所有联系人:

for循环:

    CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent ();
    long count = macContact.addressBook.people.count;
    for(int i=0;i<count;++i){
        ABPerson *person = [macContact.addressBook.people objectAtIndex:i];
        NSLog(@"%@",person);
    }
    NSLog(@"%f",CFAbsoluteTimeGetCurrent() - startTime);
for只需4秒钟就可以在addressBook中枚举5000人,而for-loop只需10分钟就可以完成同样的工作


我想知道为什么性能上会有巨大的差异?

性能上的差异几乎肯定与
macContact.addressBook.people
部分有关。您每次都通过for循环调用它,但对于for-each循环只调用一次。我猜不是
地址簿
就是
人员
属性每次都返回缓存数据,而是新数据

试用

NSArray *people = macContact.addressBook.people;
for (int i = 0; i < [people count]; i++) {
    NSLog(@"%@", [people objectAtIndex:i];
}
对于nsarray,这应该具有与For-each循环非常相似的性能。对于其他数据结构(如字典),此样式可以更快,因为它可以随键一起获取值(而For each只提供键,需要使用message send来获取值)

NSArray *people = macContact.addressBook.people;
for (int i = 0; i < [people count]; i++) {
    NSLog(@"%@", [people objectAtIndex:i];
}
[macContact.addressBook.people enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL stop){
    NSLog(@"%@", obj);
}];