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(:)
?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With