Should NSMutableArray be reversed when possible?

Suppose I have NSNumbers 1 through 450. I can add them to NSMutableArray starting from 1 and ending with 450, or starting from 450 and ending with 1. My code will be a little easier if I can start at 1 and end at 450, but when it finally comes to me to list the array, I will eventually need to cancel it. In other words, I need the first object in the enumeration to be 450, and the last to be 1.

Since my code will be simpler if I do it this way (add a start at 1 and then cancel it before listing), this is my preferred method. However, Apple's documentation for - (NSEnumerator *)reverseObjectEnumerator says:

It is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Quick listing is available on Mac OS X v10.5 and later and iOS 2.0 and later.

So should I avoid array access and just write a little more complicated code so that NSMutableArray is created in the right order first?

+4
source share
2 answers

You can use quick enumeration with an NSEnumerator instance, the quick enumeration documentation even uses the reverseObjectEnumerator: method reverseObjectEnumerator: as an example:

 NSEnumerator *enumerator = [array reverseObjectEnumerator]; for (NSString *element in enumerator) { //... } 

Also, your question sounds just like premature optimization ...

+7
source

No, you do not need to write more complex code to put it in the correct order. The reverseObjectEnumerator handler will work fine, it is only slightly slower. If performance is a big issue, then any of the snippets below will work well (the faster the while loop)

 // Assuming 'array' is your NSMutableArray int i = [array count]; while(i--) { Object *current = [array objectAtIndex:i]; // Mess around with current } 

This will start you at level 450 and end at 0. You can also do this with a for loop, although you need to make sure that you either start at index 449 or do something like

 for(int i = [array count]; i > 0 ; i--) { Object *curreyt = [array objectAtIndex:i-1]; // Mess around with current } 
+1
source

All Articles