快速的方法来存储和检索Objective-C中的数字对

我正在实现排队洪水填充algorithm,并需要存储和检索NSMutableArray的数字对。

基本上,我正在创build一个数组

 m_queue = [NSMutableArray array]; 

然后在某个时候填充数组

 [m_queue addObject:[NSValue valueWithCGPoint:CGPointMake(x + 1, y)]]; 

然后我检索下一个迭代的数据,并删除数组的开始处的值

 NSValue* value = [m_queue objectAtIndex:0]; [m_queue removeObjectAtIndex:0]; CGPoint nextPoint = [value CGPointValue]; [self queueFloodFill8:nextPoint.xy:nextPoint.y]; 

问题是:我能做些什么来避免创build大量的CGPointNSValue对象?

我真的不需要点,algorithm使用成对的整数值,所以我认为可能有更好的方式来存储这样的对。

更新:我看着实施C风格的解决scheme,如@mattjgalloway和@CRDbuild议。

我介绍过

 typedef struct lookup_point_struct { int x; int y; struct lookup_point_struct* next; } LookupPoint; 

并重写了代码,以使用此类结构的链接列表而不是NSMutableArrayCGPoint / NSValue

所有这些使我的代码快了大约3倍。 内存消耗也大幅下降。

除了可以创build自己的类(如NumberPair或者将其放入数组中而不是使用NSValueCGPoint之外,实际上没有更好的Objective-C / Foundation方法。 这可能会稍微更有效率的内存,你可以使NumberPair包含两个整数,而不是像你所关心的浮动。 就像是:

 @interface NumberPair : NSObject @property (nonatomic, assign) int x; @property (nonatomic, assign) int y; @end @implementation NumberPair @synthesize x, y; @end ... m_queue = [NSMutableArray array]; NumberPair *newPair = [[NumberPair alloc] init]; newPair.x = 1; newPair.y = 2; [m_queue addObject:newPair]; ... NumberPair *nextPoint = [m_queue objectAtIndex:0]; [m_queue removeObjectAtIndex:0]; [self queueFloodFill8:nextPoint.xy:nextPoint.y]; 

除此之外,你可以做一个更类似于C的struct包含两个整数,创build一个dynamic分配的数组来存储结构(你需要知道队列的最大尺寸或者保持重新分配)。 就像是:

 typedef struct { int x; int y; } NumberPair; NumberPair *m_queue = (NumberPair*)malloc(sizeof(NumberPair) * QUEUE_SIZE); // ... etc 

此外,你可能想看看我的MJGStack类包装NSMutableArray提供一个像接口堆栈,你可能会稍微调整,以做你想要的,而不是直接使用NSMutableArray 。 尽pipe这不是必需的。

你期望你的m_queue数组有m_queue

如果NSMutableArrayNSValue对象的成本( CGPoint是一个结构体,没有真正的成本)正在影响你的algorithm,那么考虑使用一个C风格的结构数组作为循环缓冲区以及两个队列前/后的索引。 你可以把这个抽象成一个队列类(或者如果需要,可以使用函数来保存dynamic方法调用的开销)。

如果你需要处理一个无界的队列,你可以根据需要使用你的队列类/ adt mallocrealloc数组(这基本上是NSMutableArray在幕后做的,但是它的通用性会带来更多的开销)。