快速的方法来存储和检索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大量的CGPoint
和NSValue
对象?
我真的不需要点,algorithm使用成对的整数值,所以我认为可能有更好的方式来存储这样的对。
更新:我看着实施C风格的解决scheme,如@mattjgalloway和@CRDbuild议。
我介绍过
typedef struct lookup_point_struct { int x; int y; struct lookup_point_struct* next; } LookupPoint;
并重写了代码,以使用此类结构的链接列表而不是NSMutableArray
和CGPoint
/ NSValue
。
所有这些使我的代码快了大约3倍。 内存消耗也大幅下降。
除了可以创build自己的类(如NumberPair
或者将其放入数组中而不是使用NSValue
和CGPoint
之外,实际上没有更好的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
?
如果NSMutableArray
和NSValue
对象的成本( CGPoint
是一个结构体,没有真正的成本)正在影响你的algorithm,那么考虑使用一个C风格的结构数组作为循环缓冲区以及两个队列前/后的索引。 你可以把这个抽象成一个队列类(或者如果需要,可以使用函数来保存dynamic方法调用的开销)。
如果你需要处理一个无界的队列,你可以根据需要使用你的队列类/ adt malloc
& realloc
数组(这基本上是NSMutableArray
在幕后做的,但是它的通用性会带来更多的开销)。
- 如何在目标c中使用Google自定义search进行图片search
- MathJax在UIWebView中完成加载时检测
- UICollectionViewCell带圆角和投影不起作用
- 如何检测NSAttributedString是否包含NSTextAttachment并将其删除?
- iOS中的embedded字体:为什么它们不能正确居中在y轴上?
- 如何通过htmlselect标签创buildUIPickerView的对象引用
- 如何从另一个xib视图中的一个xibembeddedUIViewController的视图?
- 如何使用Swift关闭打开的文件?
- locationManager避免(null)string在一个标签