Assume I have NSNumbers 1 - 450. I can choose to add them to an NSMutableArray either starting with 1 and ending with 450, or starting with 450 and ending with 1. My code would be a little simpler if I could start with 1 and end with 450, but when the time finally comes for me to enumerate over the array, I will ultimately need to reverse it. In other words, I need the first object in the enumeration to be 450, and the last one to be 1.
Since my code would be simpler if I do it this way (add starting with 1, then reverse it prior to enumeration), it's my preferred method. However, the Apple documentation for - (NSEnumerator *)reverseObjectEnumerator
says:
It is more efficient to use the fast enumeration protocol (see NSFastEnumeration). Fast enumeration is available on Mac OS X v10.5 and later and iOS 2.0 and later.
So should I avoid the array reversal and simply write slightly more complicated code so that the NSMutableArray gets created in the desired order in the first place?
You can use fast enumeration with an NSEnumerator
instance, the documentation about fast enumeration even uses the reverseObjectEnumerator:
method as an example:
NSEnumerator *enumerator = [array reverseObjectEnumerator];
for (NSString *element in enumerator) {
//...
}
Besides, your question sounds a lot like premature optimization...
No, you do not need to write the more complicated code to put it in the right order. The reverseObjectEnumerator will work fine, it is only marginally slower. If performance is a big concern, either of the snippets below will work well (the faster of the two being the while loop)
// Assuming 'array' is your NSMutableArray
int i = [array count];
while(i--) {
Object *current = [array objectAtIndex:i];
// Mess around with current
}
That will start you at 450 and end at 0. You can also do this with a for loop, though you need to make sure that you either start with index 449, or you do something like
for(int i = [array count]; i > 0 ; i--) {
Object *curreyt = [array objectAtIndex:i-1];
// Mess around with current
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With