Cocoa NSArray / NSSet:-makeObjectsPerformSelector:与快速枚举 [英] Cocoa NSArray/NSSet: -makeObjectsPerformSelector: vs. fast enumeration
问题描述
我想对存储在 NSSet
中的多个对象执行相同的操作。
I want to perform the same action over several objects stored in a NSSet
.
我的第一次尝试是使用快速枚举:
My first attempt was using a fast enumeration:
for (id item in mySetOfObjects)
[item action];
然后我想:
[mySetOfObjects makeObjectsPerformSelector:@selector(action)];
现在,我不知道什么是最好的选择。据我所知,这两个解决方案是等价的。
And now, I don't know what is the best choice. As far as I understand, the two solutions are equivalent. But are there arguments for preferring one solution over the other?
推荐答案
我会争论使用 makeObjectsPerformSelector
,因为它允许NSSet对象处理自己的索引,循环和消息分派。编写NSSet代码的人最有可能知道实现该特定循环的最佳方式。
I would argue for using makeObjectsPerformSelector
, since it allows the NSSet object to take care of its own indexing, looping and message dispatching. The people who wrote the NSSet code are most likely to know the best way to implement that particular loop.
在最坏的情况下,他们只是实现完全相同的循环,你的增益是稍微干净的代码(不需要包围循环)。
At worst, they would simply implement the exact same loop, and all you gain is slightly cleaner code (no need for the enclosing loop). At best, they made some internal optimizations and the code will actually run faster.
The topic is briefly mentioned in Apple's Code Speed Performance document, in the section titled "Unrolling Loops".
如果你关心性能,最好的办法是设置一个快速程序,对集合中的对象执行一些选择器。它运行几百万次,并计算两种不同情况之间的差异。
If you're concerned about performance, the best thing to do is set up a quick program which performs some selector on the objects in a set. Have it run several million times, and time the difference between the two different cases.
这篇关于Cocoa NSArray / NSSet:-makeObjectsPerformSelector:与快速枚举的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!