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(:)?
Is there any different between for(;;) and for(:) in terms of performance in Objective-C?
Share
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. Thefor(in)construction uses a protocol calledNSFastEnumerationto 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:which requires one message-send per iteration, and it’s faster than:
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.