gpt4 book ai didi

cocoa:为什么 for-each 比 for 循环更快?

转载 作者:行者123 更新时间:2023-12-03 16:17:59 25 4
gpt4 key购买 nike

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

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 秒就枚举了地址簿中的 5000 个人,而 for-loop 则需要 10 分钟才能完成同样的工作。

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

最佳答案

性能差异几乎肯定与 macContact.addressBook.people 部分有关。您在 for 循环中每次都调用它,但在 for-each 循环中仅调用一次。我猜测 addressBookpeople 属性每次都不会返回缓存数据,而是返回新数据。

尝试使用

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

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

<小时/>

也就是说,for-each 比一般情况下的 for 更快。原因是 for 循环在每次循环时都会调用 send 方法 (-objectAtIndex:),而 for-each 可以通过大批量抓取对象来更有效地获取对象。

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

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

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

关于cocoa:为什么 for-each 比 for 循环更快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12103284/

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