Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 629
adib Avatar asked Dec 09 '11 08:12

adib


2 Answers

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.

like image 81
DarkDust Avatar answered Nov 18 '22 01:11

DarkDust


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.

like image 40
Parag Bafna Avatar answered Nov 18 '22 03:11

Parag Bafna