Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the advantage of using arrayWithCapacity

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]?

like image 461
Edward Anthony Avatar asked Jul 25 '14 14:07

Edward Anthony


1 Answers

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).

like image 80
azsromej Avatar answered Oct 16 '22 08:10

azsromej