Reputation: 24018
I have been using Objective-C recently, and, coming from the C++ world, I don't get the point of specifying a capacity for the native Objective-C collections.
In C++, containers can be either filled with objects or reference types (e.g., reference wrappers or pointers), therefore specifying an initial capacity makes sense, because pre-allocating memory for a sequence of large objects can be a big performance improvement. However, in Objective-C, collections can only contain references to dynamically allocated objects, i.e., pointers. As a consequence, I wonder what's the performance advantage of specifying a capacity if, in the worst case, just pointers will need to be copied if the size of the collection is to exceed the original capacity.
Clearly, there is a lack in my understanding of the memory model, so what am I missing?
Upvotes: 2
Views: 81
Reputation: 846
Many Cocoa methods were implemented in OS X in its initial release, and quite possibly were implemented as far back as OpenStep or even NextStep. This means that they may have performed a significant role when maximizing performance on a 25MHz Motorola 68030 32-bit processor from the past. Beginning programmers can be spoiled by modern machines with gigabytes of memory and processor cycles measured in gigahertz, but older veteran programmers have developed many high-performance apps on machines with orders-of-magnitude less memory, CPU power and memory bandwidth than today's machines. It might have been extremely beneficial to save the memory reallocation time for thousands of array additions by allocating the required memory ahead of time.
I apologize for not being able to simply add a comment to the OP's post, but I felt like the idea of legacy usage required some additional perspective. It's always good to examine headers and take note of when any particular method was initially made available because it might have had significant importance in the past.
Update: From what I can locate online in publicly-maintained NextStep developer docs, it looks like NSMutableArray -initWithCapacity: and + arrayWithCapacity: were implemented at least as far back as 1994 in NextStep 3.3.
Upvotes: 3