Search code examples
cocoaperformancensmutablearraycapacity

NSMutableArray initWithCapacity nuances


Does anyone have advice on how to best initialize an NSMutableArray when it comes to dictating the capacity? The documentation mentions that "...even though you specify a size when you create an array, the specified size is regarded as a “hint”; the actual size of the array is still 0." So...

1) If I init with a greater capacity than I typically use, do I not have to worry about wasted memory?

2) If I init with a capacity typically lower than what I use, do I have to worry about heavier processing time allocating more memory to hold the extra elements?

Just how impacting is this initialized capacity to the performance/memory usage of this data type?


Solution

  • Whether any space is wasted by giving too big a capacity is actually an implementation detail that Apple deliberately doesn't expose, I guess. NSMutableArray is a class cluster which means you don't actually get an instance of NSMutableArray but some other, specialized class following the same interface. And Apple doesn't tell you which class gets returned in which case and how it's behaving. So it's hard to give real advices here.

    If you really know that on average you'll need a capacity of X, just use it. Otherwise, unless you have performance problems I wouldn't care about the capacity at all and just use [NSMutableArray array]...