-3

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.

brandonscript
  • 68,675
  • 32
  • 163
  • 220
  • 2
    What is happening in `// stuff!`? – mipadi May 12 '15 at 22:21
  • It is relevant. For example, if you're initializing an array, for example, to a constant value, there are fast ways to do that. In the general case, no, this `for` loop is the fastest (and most likely, it's *not* going to be a bottleneck). – mipadi May 12 '15 at 22:22
  • @mipadi I want to know if I can do this specifically using fast enumeration blocks. Either it can, or cannot, be done. Block already would include the necessary bits for enumerating. – brandonscript May 12 '15 at 22:23
  • 2
    If your question is "How do I do this in the fastest way?" then `// stuff!` is **absolutely** relevant, and as long as you think it's irrelevant, this question isn't very useful. – nhgrif May 12 '15 at 22:25
  • @remus: Well, in that case, no, incrementing an integer counter is most likely the fastest way you can do this sort of for loop. – mipadi May 12 '15 at 22:26
  • Unless you're enumerating a collection, using fast enumeration or blocks don't make much sense. Like the others said, what's you're trying to do is the important part here. – Jon Shier May 12 '15 at 22:27

1 Answers1

5

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.

Rob Napier
  • 286,113
  • 34
  • 456
  • 610