These methods are actually part of NSMutableArray , not NSArray .
It gives a hint about how many items you like to store, so it can already allocate enough memory ahead, rather than increase the memory as necessary, which can be costly because it may require allocation, copying from the old memory to the new one, freeing up the old memory . And if you add a lot of elements, this increase can happen a lot, so itβs more efficient if NSMutableArray can allocate the required amount of memory at a time.
Remember that this is just a hint and the implementation may ignore it. In fact, CFArray/CFMutableArray ignores capacity when creating a mutable array:
static CFArrayRef __CFArrayInit(CFAllocatorRef allocator, UInt32 flags, CFIndex capacity, const CFArrayCallBacks *callBacks) { struct __CFArray *memory; UInt32 size; ... switch (__CFBitfieldGetValue(flags, 1, 0)) { case __kCFArrayImmutable: size += capacity * sizeof(struct __CFArrayBucket); break; case __kCFArrayDeque: case __kCFArrayStorage: break; } ... return (CFArrayRef)memory; } CFMutableArrayRef CFArrayCreateMutable(CFAllocatorRef allocator, CFIndex capacity, const CFArrayCallBacks *callBacks) { ... return (CFMutableArrayRef)__CFArrayInit(allocator, __kCFArrayDeque, capacity, callBacks); }
According to this article related to @azsromej, NSMutableArray also seems to ignore the hint.
source share