Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for(;;) vs. for(:) in Objective-C Performance and Practice

Tags:

objective-c

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(:)?

like image 790
Ryan Rho Avatar asked Aug 19 '11 07:08

Ryan Rho


1 Answers

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.

like image 117
Graham Lee Avatar answered Nov 15 '22 07:11

Graham Lee