objective-cobjective-c-blocksfast-enumeration

Objective-C can you use fast enumeration in place of "for (i = 0; i < X; i++)"


Let's say I've got a basic integer iteration like so:

NSInteger rowCount = self.rowCount;
for (int i = 0; i < rowCount; i++) {
    // stuff!
}

Is there a way to implement this using fast enumeration blocks? I could certainly create an array of integers 0 - self.RowCount, but that doesn't seem like it'd be more performant than just doing it this way.


Solution

  • No. Fast enumeration is a technique for maintaining iteration state such that iteration over collections is more efficient. It overcomes the fact that many collections do not index in O(1), so iterating over them via indexing would be something greater than O(N). Even collections that do index in O(1) may suffer a large constant time due to the cost of a method call (such as objectAtIndex:). If you look at the NSFastEnumeration protocol, you'll notice that it relies on creating C-arrays that are highly efficient to index.

    A for loop that increments an integer (that can likely be optimized into a register) doesn't have the same problem, and fast enumeration would not provide a solution.

    Of course if // stuff! did include indexing into self, then fast enumeration would be much better (and you shouldn't use indexes at all), but the question implies that this isn't the case.