Reputation: 145
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?
Upvotes: 3
Views: 278
Reputation: 130102
It's a higher lever language structure, therefore it can do better optimizations:
For example, consider iterating an 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.
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!).
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.
Upvotes: 5