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(:)
?
-
11Two semicolons make a colon, so they are exactly equivalent.– Steven SchlanskerCommented 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 RhoCommented Aug 19, 2011 at 7:48
-
1This would be so easy to just build a test case for each loop style and do some profiling runs.– Patrick HughesCommented Aug 19, 2011 at 8:00
-
1How does the performance of an infinite loop matter?– IngoCommented 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 RhoCommented Aug 19, 2011 at 8:34
1 Answer
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.