简体   繁体   中英

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?

@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 greatest virtues are flexibility and reuse. 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. Unless your array operations are very complex and the arrays very large eg 10K+ objects, you probably won't see any significant performance differences.

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.

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. If you use std::stack you will have to add stuff in to do memory management.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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