I am implementing queued flood fill algorithm and need to store and retrieve pairs of numbers in NSMutableArray.
Basically, I am creating an array
m_queue = [NSMutableArray array];
then at some time I populate the array
[m_queue addObject:[NSValue valueWithCGPoint:CGPointMake(x + 1, y)]];
then I retrieve data for the next iteration and remove the value at the beginning of the array
NSValue* value = [m_queue objectAtIndex:0];
[m_queue removeObjectAtIndex:0];
CGPoint nextPoint = [value CGPointValue];
[self queueFloodFill8:nextPoint.x y:nextPoint.y];
The question is: what can I do to avoid creating large number of CGPoint and NSValue objects?
I don’t really need points, the algorithm uses pairs of integer values, so I think there might be a better way to store such pairs.
UPDATE:
I looked into implementing C-style solution like @mattjgalloway and @CRD suggested.
I’ve introduced
typedef struct lookup_point_struct
{
int x;
int y;
struct lookup_point_struct* next;
} LookupPoint;
and have rewritten code to use linked list of such structs instead of NSMutableArray and CGPoint/NSValue.
All this made my code about 3 times faster. And memory consumption dropped significantly too.
There wouldn’t really be a better Objective-C / Foundation way of doing it, apart from maybe creating your own class such as
NumberPairor something which you put into the array rather than usingNSValueandCGPoint. It might be slightly more memory efficient to do that and you could makeNumberPaircontain two integers rather than floats like you are concerned about. Something like:Other than that you could do a more C-like thing of having a
structcontaining two integers, create a dynamically allocated array to store the structs (you’d need to know the max size of the queue or keep reallocating). Something like:Also, you might want to check out my MJGStack class which wraps
NSMutableArrayto provide a stack like interface which you might be able to adjust slightly to do what you want rather than usingNSMutableArraydirectly. Although that’s not essential by any means.