我正在实现排队洪水填充算法,需要存储和检索数字对NSMutableArray
.
基本上,我正在创建一个数组
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.x y:nextPoint.y];
问题是:我该怎么做才能避免创建大量CGPoint
and NSValue
物体?
我真的不需要点,该算法使用整数值对,所以我认为可能有更好的方法来存储这些对。
UPDATE:我研究了实现 C 风格的解决方案,如@mattjgalloway 和@CRD 建议的。
我已经介绍过
typedef struct lookup_point_struct
{
int x;
int y;
struct lookup_point_struct* next;
} LookupPoint;
并重写了代码以使用此类结构的链接列表而不是NSMutableArray
and CGPoint
/NSValue
.
所有这些使我的代码速度提高了大约 3 倍。内存消耗也显着下降。
除了创建您自己的类(例如NumberPair
或者你放入数组而不是使用的东西NSValue
and CGPoint
。这样做可能会稍微提高内存效率,你可以这样做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.x y:nextPoint.y];
除此之外你可以做一个更像C的事情struct
包含两个整数,创建一个动态分配的数组来存储结构(您需要知道队列的最大大小或继续重新分配)。就像是:
typedef struct {
int x;
int y;
} NumberPair;
NumberPair *m_queue = (NumberPair*)malloc(sizeof(NumberPair) * QUEUE_SIZE);
// ... etc
另外,您可能想查看我的MJGStack https://github.com/mattjgalloway/MJGFoundation/blob/master/Source/Model/MJGStack.h包装类NSMutableArray
提供一个类似堆栈的界面,您可以稍微调整它来执行您想要的操作,而不是使用NSMutableArray
直接地。尽管这无论如何都不是必要的。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)