adib
adib

Reputation: 8395

Why is NSFastEnumeration fast?

Does anybody know whether NSFastEnumeration is really faster (as in run-time performance) than using NSEnumerator or (for arrays) using an integer counter and loop through the elements?

If it is indeed faster, how does it achieve that speed?

Or perhaps the "fast" actually refers to faster in writing the iteration code?

Thanks in advance.

Upvotes: 8

Views: 1388

Answers (2)

DarkDust
DarkDust

Reputation: 92336

Depending on the container, NSFastEnumeration is at least as fast as NSEnumerator but usually much faster since it involves fewer method calls.

Instead of having to call nextObject for every item in the array, with NSFastEnumerator the array can give back a block of objects in a C array at once. Iterating that C array is way faster than having to do lots of method calls, which each look up and return just one object.

Upvotes: 6

Parag Bafna
Parag Bafna

Reputation: 22930

Fast enumeration is not faster than any "for" loop. In a general sense, that is impossible because basic loops are already as optimized as they can be.

Instead, fast enumeration is faster than a "for" or "while" loop that fetches data on every iteration from an Objective-C object using an Objective-C method call.

It does this by fetching the data in batches, reducing the overhead of calling a method on each iteration. Removing the method call from the inner part of the loop also has compiler optimisation benefits.

Upvotes: 5

Related Questions