Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Disadvantage of using NSMutableArray vs NSArray?

I'm using an array to store cached objects loaded from a database in my iPhone app, and was wondering: are there any significant disadvantages to using NSMutableArray that I should know of?

edit: I know that NSMutableArray can be modified, but I'm looking for specific reasons (performance, etc..) why one would use NSArray instead. I assume there would be a performance difference, but I have no idea whether it's significant or not.

like image 615
igul222 Avatar asked Nov 17 '09 02:11

igul222


People also ask

What is the key 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.

Can we use NSArray in Swift?

In Swift, the NSArray class conforms to the ArrayLiteralConvertible protocol, which allows it to be initialized with array literals. For more information about object literals in Swift, see Literal Expression in The Swift Programming Language (Swift 4.1).

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 .

Can NSArray contain nil?

arrays can't contain nil.


1 Answers

If you're loading objects from a database and you know exactly how many objects you have, you would likely get the best performance from NSMutableArrays arrayWithCapacity: method, and adding objects to it until full, so it allocates all the memory at once if it can.

Behind the scenes, they're secretly the same thing - NSArray and NSMutableArray are both implemented with CFArrays via toll free bridging (a CFMutableArrayRef and a CFArrayRef are typedef's of the same thing, __CFArray *) *

NSArray and NSMutableArray should have the same performance/complexity (access time being O(lg N) at worst and O(1) at best) and the only difference being how much memory the two objects would use - NSArray has a fixed limit, while NSMutableArray can use up as much space as you have free.

The comments in CFArray.h have much more detail about this.

*: As Catfish_Man points out below, this isn't true anymore.

like image 121
zadr Avatar answered Oct 02 '22 15:10

zadr