arrayWithCapacity
is a method defined in NSArray.h and implemented in NSArray.m
When I look at the code that GNUStep provided, I can get that arrayWithCapacity
is a normal method that calls initWithCapacity
:
+ (id) arrayWithCapacity: (NSUInteger)numItems
{
return AUTORELEASE([[self allocWithZone: NSDefaultMallocZone()]
initWithCapacity: numItems]);
}
And initWithCapacity
is a simple method that only does self initialization.
- (id) initWithCapacity: (NSUInteger)numItems
{
self = [self init];
return self;
}
Nothing about memory allocation with number of items executed.
What is the advantage of using the arrayWithCapacity
method? Is it better to simply use [[NSArray alloc] init]
?
The expectation is that providing an explicit size improves memory allocation as there's no need to adjust the size of the array as items are added. In practice, it is just a hint and there's some evidence that it's not actually used (see this objc.io article on The Foundation Collection Classes).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With