5

Is there any different between for(;;) and for(:) in terms of performance in Objective-C? And what are good practices to use for(;;) or for(:)?

6
  • 11
    Two semicolons make a colon, so they are exactly equivalent. Commented Aug 19, 2011 at 7:31
  • Hahaha good point.I believe there may be some difference in performance like any other languages such as Javascript and C#.
    – Ryan Rho
    Commented Aug 19, 2011 at 7:48
  • 1
    This would be so easy to just build a test case for each loop style and do some profiling runs. Commented Aug 19, 2011 at 8:00
  • 1
    How does the performance of an infinite loop matter?
    – Ingo
    Commented Aug 19, 2011 at 8:13
  • Sorry for the confusion. I didn't mean infinite loops. I meant using for statements with either semicolons and colons.
    – Ryan Rho
    Commented Aug 19, 2011 at 8:34

1 Answer 1

11

I'll assume that in each case you are enumerating a collection of objects, as only the C for(;;) form allows enumeration of primitive types. The for(in) construction uses a protocol called NSFastEnumeration to fill a buffer with objects to use in future iterations, and uses a cursor to track which object it's got up to. That makes it faster than:

NSEnumerator *e = [collection objectEnumerator];
while (id o = [e nextObject]) {
  //...
}

which requires one message-send per iteration, and it's faster than:

for (NSInteger i=0; i < [collection count]; i++) {
  id o = [collection objectAtIndex: i];
  //...
}

which also requires one message-send per iteration[*]. The for(in) construct only requires a message send every time the buffer runs dry, which might be once every 8 iterations or so.

Notice that there's also block-based looping with [collection enumerateObjectsUsingBlock: ^(id obj, int idx, BOOL *stop){/*...*/}]; which has different properties again. Particularly the version of this construction that takes options can be told to execute the blocks concurrently.

[*]Observant readers will notice that this actually requires two message sends per iteration, as the termination condition will be evaluated every time through; however it's so easy to reduce that to one message send that we'll treat it as one for this discussion.

Not the answer you're looking for? Browse other questions tagged or ask your own question.