fiacobelli
fiacobelli

Reputation: 1990

What's the advantage of fast enumeration versus a c style for loop in Objective C?

I've been using c style enumeration in objective C when I need to know at which index the object is. However, apple recommends a different style. So, they recommend that:

for(int i=0;i<array.count;i++)
    NSLog(@"Object at index %i is: %@", i, array[i]);

be changed to

int index = 0;
for (id eachObject in array) {
   NSLog(@"Object at index %i is: %@", index, eachObject);
   index++;
}

Is there a good reason for this other than stylistic preference?

And a follow up: How would one enumerate the letters in a String using the second kind of enumeration?

Upvotes: 1

Views: 313

Answers (3)

Manny
Manny

Reputation: 977

A while back someone analyzed the different enumeration options for an NSArray. The results are very interesting. It's worth noting that the tests were done on iOS4 and OSX 10.6 though.

http://darkdust.net/writings/objective-c/nsarray-enumeration-performance

In general, he shows that when dealing with something other than very small arrays, fast enumeration is better performing than block enumeration, and both are better performing than basic enumeration (array[i]).

It would be great to see these tests on iOS7!

Upvotes: 1

Gavin
Gavin

Reputation: 8200

Fast enumeration, the second option, can be better optimized by the compiler. So besides resulting in cleaner looking code that doesn't have to track the index, you also end up with faster code. So any time the second option would work, it likely should be used.

Now if you wanted to iterate over the characters in an NSString, you couldn't by default do that using fast enumeration. The only way you could do it is if you first put the characters into an NSArray, most likely using a standard for loop to iterate over the characters and add them manually. But this would defeat the purpose of using fast iteration in the first place since you have to do a standard for loop first anyway. You would only do this if you wanted to do fast iteration over this same string of text many many times, and could add them to an array first just once.

Upvotes: 1

Alessandro Roaro
Alessandro Roaro

Reputation: 4733

The advantage is simply that it's faster to write and easier to read. It's especially useful when you don't need the index (i for example) other than for accessing the object.

Upvotes: 0

Related Questions