All of the collection classes have two versions – mutable and immutable, such as NSArray and NSMutableArray. Is the distinction merely to promote careful programming by providing a const collection or is there some performance hit when using a mutable object as opposed to immutable?
Similarly each of the collection classes has a method xxxxWithCapacity, like
[NSMutableArray arrayWithCapacity:0]. I often use zero as the argument because it seems a better choice than guessing wrongly how many objects might be added. Is there some performance advantage to creating a collection with capacity for enough objects in advance? If not why isn’t the function something like + (id)emptyArray?
Is there some performance advantage to creating a collection with capacity for enough objects in advance?
If you reserve space for your mutable array ahead of time, you don’t have the overhead of resizing an empty or small array as objects are added. Resizing can involve holding objects in place, setting up a sufficiently large, new chunk of space on the heap, and then possibly moving those objects to the new spot in memory.
Whereas, if you specify the space you need in advance, you don’t have this resizing to deal with. You have that chunk of space and you can just put objects in there.