Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is NSMutableArray better than NSArray for memory reasons?

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

like image 872
Vik Singh Avatar asked Jan 24 '13 03:01

Vik Singh


People also ask

When should we prefer NSMutableArray over NSArray?

NSArray is used to hold an immutable array of objects and the NSMutableArray is used to hold an mutable array of objects.

What is difference between NSArray and NSMutableArray?

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.

Which is faster NSArray or NSMutableArray?

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).

What is NSMutableArray?

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 .


2 Answers

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.

like image 72
Catfish_Man Avatar answered Sep 20 '22 00:09

Catfish_Man


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.

like image 28
Jack Avatar answered Sep 20 '22 00:09

Jack