Reputation: 1603
I have a question regarding NSArray and NSMutableArray. I understand the difference between two primarily that NSArray is immutable and NSMutableArray is mutable. And as far as my research goes, there performance is kind of same too. There is one thing that I could not find a good answer for and that is if NSMutableArray uses more memory than NSArray and if NSMutableArray is somehow harsher on memory than NSArray.
I would really appreciate the suggestions and explanation.
Thanks Vik
Upvotes: 7
Views: 1864
Reputation: 41801
NSMutableArray uses slightly more memory for two (er, four, see comments) reasons:
1) Because it can change size, it can't store the contents inside the object and must store a pointer to out of line storage as well as the extra malloc node for the storage
2) Because it would be very slow to resize one element at a time as things are added, it resizes in chunks, which may result in some unused space.
Upvotes: 13
Reputation: 8247
For normal use there is no noticeable performance difference.
However, If you return an NSArray from a method that internally uses a mutable array for building the response, then I found that a copy of the temporary array can take significant amount of time.
In some instances in DTCoreText I found the [NSMutableArray copy] to NSArray would take 40% of the method time in Instruments. I.e. Returning the mutable array halved the method time.
So when evaluating NSArray versus mutable performance I recommend you direct your attention towards avoiding copying objects. In tight loops or internal methods you should prefer to avoid copying.
Upvotes: 1
Reputation: 133567
It's like wondering about the difference between a standard array or a std::vector
. A mutable data structure does require to do more things, not primarily memory (as the one required by NSMutableArray
and NSArray
could be equal) but it requires to be dynamically resizable and to manage all specific operations like insertions and removals which are not necessary with an immutable array: the dimension is decided when the object is allocated at it is constant.
Upvotes: 2