4

What is faster in objective C and iphone? self enumeration or for loop?

i have 2 fragments of code to help me compare.

for this example we have as a fact that array is an NSMutableArray with "x" items. Case 1:

-(void)findItem:(Item*)item
{
  Item *temp;
  for (int i = 0 ;i<[array count];i++)
  {

    temp = [array objectAtIndex:i];
    if(item.tag == temp.tag)
      return;
  }


}

Case 2:

-(void)findItem:(Item*)item
{
  for(Item *temp in array)
  {
    if(item.tag == temp.tag)
      return;
  }
}

it is almost obvious that case2 is faster, is it?

j0k
  • 22,600
  • 28
  • 79
  • 90
L_Sonic
  • 594
  • 6
  • 22
  • i actually don't know how to count runtime... – L_Sonic Jul 07 '11 at 15:19
  • 2
    It's called fast enumeration for a reason - see: http://cocoawithlove.com/2008/05/fast-enumeration-clarifications.html – petert Jul 07 '11 at 15:21
  • 1
    Then you should first research on how to measure. Then, your next research should then on how you can __properly__ measure something like this. Simply posting two snippets and begging for someone to measure exactly those two code-fragments is not appropriate in your case. – Sebastian Mach Jul 07 '11 at 15:22
  • lets talk about 10000 objects... what about then? – L_Sonic Jul 07 '11 at 15:22
  • That's a function of your problem, if you have to iterate over 10000 objects in-order. If you do some tests with fast enumeration you could report back some findings. Also try using enumeration using blocks (http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Collections/Articles/Enumerators.html#//apple_ref/doc/uid/20000135-BBCFABCB) – petert Jul 07 '11 at 15:27
  • 2
    Why do you think that it's *obvious* that case 2 is faster? – Abizern Jul 07 '11 at 15:28
  • it is obvious maybe because there isn't so many characters to write... –  Jul 07 '11 at 15:38
  • @Vince: Program execution speed is not a function of source code length. If you meant “faster to write” or more precisely “faster to type”, then yes. – Peter Hosey Jul 07 '11 at 15:50
  • 1
    Unless your array has a zillion items or you are calling that method a zillion times, it generally doesn't matter unless you measure it and it does matter. – bbum Jul 07 '11 at 16:25

1 Answers1

10

It's called fast enumeration, for a reason.

See: http://cocoawithlove.com/2008/05/fast-enumeration-clarifications.html

petert
  • 6,672
  • 3
  • 38
  • 46
  • 11
    The link only says that it is faster than using NSEnumerable, but not faster than a for loop. But this does: http://stackoverflow.com/questions/32986/nsenumerator-performance-vs-for-loop-in-cocoa – Daniel Nov 04 '11 at 12:23