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
NSArray is used to hold an immutable array of objects and the NSMutableArray is used to hold an mutable array of objects.
The primary difference between NSArray and NSMutableArray is that a mutable array can be changed/modified after it has been allocated and initialized, whereas an immutable array, NSArray , cannot.
NSMutableArray and NSArray both are build on CFArray , performance/complexity should be same. The access time for a value in the array is guaranteed to be at worst O(lg N) for any implementation, current and future, but will often be O(1) (constant time).
The NSMutableArray class declares the programmatic interface to objects that manage a modifiable array of objects. This class adds insertion and deletion operations to the basic array-handling behavior inherited from NSArray . NSMutableArray is “toll-free bridged” with its Core Foundation counterpart, CFMutableArray .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With