When I use NSMutableArray
or NSMutableDictionary
, if I know the number of elements I want to put in or the max number of elements, I usually create them with arrayWithCapacity
or dictionaryWithCapacity
, but I wonder does it really help to specify an (initial) capacity for the array/dictionary?
I don't know how it is implemented internally, but I believe it is possible that when the number of elements in a collection hits the capacity or even approaches the capacity, the collection may extend its capacity, so if I created a mutable array with capacity 32, as long as I put the 32nd object in it, it will expand itself to another capacity? Or even if I put the 30st object in it, its capacity will be expanded as it thinks there will be more objects?
So if these methods really help, should I use something like:
*withCapacity:maxNumberOfElements * 1.5
instead of
*withCapacity:maxNumberOfElements
so it will have more than enough capacity for my objects and won't expand when I put in all the objects?