Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should reversing an NSMutableArray be avoided when possible?

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?

like image 624
maxedison Avatar asked Feb 23 '23 23:02

maxedison


2 Answers

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...

like image 110
omz Avatar answered Mar 27 '23 10:03

omz


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
}
like image 32
Scott Rice Avatar answered Mar 27 '23 10:03

Scott Rice