3

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

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);

对于每个

    CFAbsoluteTime startTime = CFAbsoluteTimeGetCurrent ();
    for(ABPerson *person in macContact.addressBook.people){
        NSLog(@"%@",person);
    }
    NSLog(@"%f",CFAbsoluteTimeGetCurrent() - startTime);

for-each 只用了 4 秒就枚举了 addressBook 中的 5000 人,而 for-loop 用了 10 分钟来完成同样的工作。

我想知道为什么性能差异很大?

4

1 回答 1

5

性能上的差异几乎肯定与macContact.addressBook.people零件有关。您每次都通过 for 循环调用它,但只有一次使用 for-each 循环。我猜要么 要么addressBook属性people每次都不会返回缓存数据,而是返回新数据。

尝试使用

NSArray *people = macContact.addressBook.people;
for (int i = 0; i < [people count]; i++) {
    NSLog(@"%@", [people objectAtIndex:i];
}

您可能会再次发现性能非常相似。


也就是说,for-each 通常比 for 更快。原因是 for 循环在每次通过循环-objectAtIndex:

在最新版本的操作系统中,您可以更进一步,使用基于块的枚举方法。这看起来像

[macContact.addressBook.people enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL stop){
    NSLog(@"%@", obj);
}];

对于 NSArrays,这应该具有与 for-each 循环非常相似的性能。对于诸如字典之类的其他数据结构,这种样式可能更快,因为它可以随键一起获取值(而 for-each 只为您提供键并要求您使用消息发送来获取值)。

于 2012-08-24T04:50:35.683 回答