0
NSEnumerator* friendsEnumerator = [friends objectEnumerator];

id aFriend;

while ((aFriend = [friendsEnumerator nextObject])) {

  printf("%s\n", [aFriend UTF8String]);

}


int friendsCount = [friends count];

for(int i = 0; i < friendsCount; i++) {

  printf("%s\n", [[friends objectAtIndex: i] UTF8String]);

}


for(NSString* aFriend in friends) {

  printf("%s\n", [aFriend UTF8String]);

}
Bug
  • 2,576
  • 2
  • 21
  • 36
mani murugan
  • 213
  • 2
  • 12
  • Aren't 1 and 3 the same thing? I think you'll need to profile it to find out. – trojanfoe Oct 01 '13 at 10:00
  • 2
    Logging inside a loop will slow it down to the point where the differences between these will be pretty insignificant... – Carl Veazey Oct 01 '13 at 10:03
  • if you want to check performance ALWAYS do a measurements. If you ask people they will give you answer based on they knowledge or experience but this doesn't have to be reproducible for your code, especially that in such cases people only think they know the proper answer. – Marek R Oct 01 '13 at 10:21

3 Answers3

2

Case 3 is the fastest and generally better approach:

Fast enumeration is the preferred method of enumerating the contents of a collection because it provides the following benefits:

  • The enumeration is more efficient than using NSEnumerator directly.
    • List item
    • The syntax is concise.
    • The enumerator raises an exception if you modify the collection while enumerating. You can perform multiple enumerations concurrently.

You can read more about it here

micantox
  • 5,446
  • 2
  • 23
  • 27
2

You can enumerate an array using the below method also.The stop parameter is important for performance, because it allows the enumeration to stop early based on some condition determined within the block.

[friends enumerateObjectsUsingBlock:^(id obj, NSUInteger index, BOOL *stop){

 if ('some condition') {
      NSLog(@"Object Found: %@ at index: %i",obj, index);
      *stop = YES;
 }

} ];
Govind
  • 2,337
  • 33
  • 43
1

First things first: option 1 and 3 are the same in terms of operations, both use the NSFastEnumeration protocol to provide a fast access to objects in collections.

As the name "NSFastEnumeration" implies, enumerations are faster then for-loops, as they don't need array bounds checking for each single object.

So it comes down to a matter of taste between 1 and 3. Personally I prefer forin-loops as they seem to be more elegant.

Jens Ravens
  • 122
  • 6
  • [arrayName enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) { }]; what about this type of enumerations using block ? is it more speed than case 3 ? – mani murugan Oct 01 '13 at 10:12
  • 1
    I'm sorry, how are they the same when it is clearly stated that `The enumeration is more efficient than using NSEnumerator directly.` in the apple programming guide that I linked? – micantox Oct 01 '13 at 10:15
  • thanks jens..for your golden feedbacks.. – mani murugan Oct 01 '13 at 10:22