简体   繁体   English

NSMutableArray与堆栈

[英]NSMutableArray Vs Stack

I am developing 2D game for iphone in Objectice-C.In this project I need to use stack, I can do it using STL(Standard template library) stacks or NSMutableArray, since this stack is widely used in the game which one is more efficient in terms of runtime speed and memory use? 我正在用Objectice-C开发iPhone的2D游戏。在这个项目中,我需要使用堆栈,我可以使用STL(标准模板库)堆栈或NSMutableArray来完成它,因为该堆栈在游戏中得到了广泛的使用,效率更高在运行速度和内存使用方面?

@interface CarElement : NSObject
{
  std::stack<myElement*> *mBats;
}

or 要么

@interface CarElement : NSObject
{
  NSMutableArray *mBats;
}

Thanks, 谢谢,

It is generally accepted that Objective-C is slower in most cases than C++. 通常认为,Objective-C在大多数情况下比C ++慢。

Objective-C greatest virtues are flexibility and reuse. Objective-C的最大优点是灵活性和重用性。 The runtime linking that creates that flexibility imposes a considerable overhead. 创建这种灵活性的运行时链接会带来相当大的开销。

On the other hand, in the case of arrays, that overhead is usually trivial. 另一方面,对于数组,该开销通常是微不足道的。 In the case of a LIFO stack, you won't see any performance difference between Objective-C and C++ because the code doesn't have to scan the entire array but just the first element. 对于LIFO堆栈,您不会在Objective-C和C ++之间看到任何性能差异,因为代码不必扫描整个数组,而只需扫描第一个元素。 Unless your array operations are very complex and the arrays very large eg 10K+ objects, you probably won't see any significant performance differences. 除非您的阵列操作非常复杂且阵列非常大(例如10K +个对象),否则您可能不会看到任何明显的性能差异。

My advice is to do a test run with some dummy data of the type you want to manipulate in the app. 我的建议是使用您想要在应用程序中操作的一些虚拟数据进行测试运行。 Load the arrays up past the max size you expect, loop a large number of manipulations then measure time and memory use. 将阵列加载到超出您期望的最大大小,循环进行大量操作,然后测量时间和内存使用量。 See if the performance gain of C++ justifies the extra dev time and complexity tax is worth the performance gain. 看看C ++的性能提升是否足以证明额外的开发时间和复杂性税是否值得该性能提升。

Remember as well that premature optimization is the root of all evil . 还要记住, 过早的优化是万恶之源 Don't spend time futzing to prevent a problem you might not even have. 不要花太多时间来避免可能根本没有的问题。 Default to the simplest solution unless you have good evidence to suspect it may not be sufficient. 默认为最简单的解决方案,除非您有充分的证据怀疑它可能不够用。

I would use NSMutableArray, not because it is faster (it probably won't be) but because it is easier in the context of Objective-C. 我将使用NSMutableArray,不是因为它速度更快(可能不会),而是因为在Objective-C的上下文中它更容易。 If you use std::stack you will have to add stuff in to do memory management. 如果使用std :: stack,则必须添加一些内容以进行内存管理。

I'd then profile the code to find out if the stack was a bottleneck. 然后,我将分析代码以了解堆栈是否是瓶颈。 If it was, I might consider reimplementing with std::stack or even rolling my own. 如果是这样,我可能会考虑使用std :: stack重新实现,甚至自己滚动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM