I'm working on an application, I have a NSMutableArray that stores 20 or so sprites. I need to iterate through it fairly quickly and efficiently. The speed for my purposes is not optimal... I'm getting two values from each sprite as it iterates through, would it be more efficient (faster) to iterate through an array of say CGPoints then an array of sprites? Or instead of CGPoint make a custom class for the sole purpose of handling just two integer values. Either way, is speed affected by the type of objects or values stored in an array?
I don't think you should be worried about iteration speed over only 20 items.
The speed of iteration is not affected by what type of data you're storing in the array. It is affected by the type of array you're using: there are significant differences between iterating through an Objective-C NSArray
(or any of its subclasses, such as NSMutableArray
), a C-style array, or a C++ std::vector
.
If you're using an NSArray
, and you're using Objective-C 2.0 (e.g. on the iPhone or on Mac OS X 10.5 or later), you can use fast enumeration to iterate, which is significantly faster than the older style of iteration:
// Fast enumeration
for(id object in myNSArray)
; // do stuff with object
// Slow enumeration
int count = [myNSArray count], i;
for(i = 0; i < count; i++)
{
id object = [myNSArray objectAtIndex:i];
// do stuff with object
}
I'm not sure how fast enumeration compares with C-style arrays or C++ std::vector
s, but I would bet that it's still a little bit slower. It's slower because you have the extra overhead of Objective-C: passing messages (such as count
and objectAtIndex:
) goes through the Objective-C runtime, which is slower than bare pointer arithmetic even in the best case.
Iterating through a C-style array or a C++ std::vector
is very fast, since the compiler can optimize them to really simple pointer arithmetic instructions with no overhead:
// C-style array
SomeType *myArray = ...; // e.g. malloc(myArraySize * sizeof(SomeType))
int i;
for(i = 0; i < myArraySize; i++)
; // do stuff with myArray[i]
// C++ vector
std::vector<SomeType> myArray = ...;
for(std::vector<SomeType>::iterator i = myArray.begin(); i != myArray.end(); ++i)
; // do stuff with *i