Cocoa 为什么for-each比for-loop快?
我的应用程序以两种方式读取所有联系人: for循环: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];
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);
}];