I know that what is fast enumeration and it's purpose in objective C. I want to know why fast enumeration is more faster than normal iteration?
我知道什么是快速枚举,它在objective c中的作用,我想知道为什么快速枚举比常规迭代快?
1 个解决方案
#1
5
It's a higher lever language structure, therefore it can do better optimizations:
它是一种更高的杠杆语言结构,因此可以做更好的优化:
For example, consider iterating an NSArray
:
例如,考虑迭代一个NSArray:
for (NSUInteger i = 0; i < [array count]; i++) {
id object = [array objectAtIndex:i];
}
For every iterations, there are two method calls. .count
is a method call. .objectAtIndex
is a method call. Method calls are slow.
对于每个迭代,都有两个方法调用。.count是一个方法调用。。objectatindex是一个方法调用。方法调用是缓慢的。
While we can fix the first, e.g.
我们可以先解决第一个问题。
NSUInteger count = [array count];
for (NSUInteger i = 0; i < count; i++) {
We cannot fix the second.
我们无法解决第二个问题。
Fast enumeration can load the items into a C array and iterate over them fast, without the need to call methods. Also, another great improvement is to reduce checks whether i
is inside the bounds of the array (with a for i
that needs one comparison for every iteration!).
快速枚举可以将项加载到C数组中并快速遍历它们,而不需要调用方法。另外,另一个很大的改进是减少检查是否在数组的范围内(对于我来说,每一次迭代都需要一个比较!)
Of course, there are more possible improvements but the important thing is letting the compiler know what we want to do without telling it how exactly we want to do that. The compiler can do the task better than us.
当然,还有更多可能的改进,但重要的是让编译器知道我们想要做什么,而不告诉它我们到底想做什么。编译器能比我们做得更好。
#1
5
It's a higher lever language structure, therefore it can do better optimizations:
它是一种更高的杠杆语言结构,因此可以做更好的优化:
For example, consider iterating an NSArray
:
例如,考虑迭代一个NSArray:
for (NSUInteger i = 0; i < [array count]; i++) {
id object = [array objectAtIndex:i];
}
For every iterations, there are two method calls. .count
is a method call. .objectAtIndex
is a method call. Method calls are slow.
对于每个迭代,都有两个方法调用。.count是一个方法调用。。objectatindex是一个方法调用。方法调用是缓慢的。
While we can fix the first, e.g.
我们可以先解决第一个问题。
NSUInteger count = [array count];
for (NSUInteger i = 0; i < count; i++) {
We cannot fix the second.
我们无法解决第二个问题。
Fast enumeration can load the items into a C array and iterate over them fast, without the need to call methods. Also, another great improvement is to reduce checks whether i
is inside the bounds of the array (with a for i
that needs one comparison for every iteration!).
快速枚举可以将项加载到C数组中并快速遍历它们,而不需要调用方法。另外,另一个很大的改进是减少检查是否在数组的范围内(对于我来说,每一次迭代都需要一个比较!)
Of course, there are more possible improvements but the important thing is letting the compiler know what we want to do without telling it how exactly we want to do that. The compiler can do the task better than us.
当然,还有更多可能的改进,但重要的是让编译器知道我们想要做什么,而不告诉它我们到底想做什么。编译器能比我们做得更好。