I have a method to build and return an array:
- (NSArray *)foo
{
NSUInteger capacity = [self getArrayCapacity];
if (capacity == 0) {
return @[];
} else {
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:capacity];
// add elements to the array, as many as capacity
...
return array;
}
}
Is there a difference in memory used or performance if I simplify the code as follows:
- (NSArray *)fooSimplified
{
NSUInteger capacity = [self getCapacity];
NSMutableArray *array = [[NSMutableArray alloc] initWithCapacity:capacity];
// add elements to the array, as many as capacity
...
return array;
}
}
So when capacity == 0
instead of returning @[]
it would return [[NSMutableArray alloc] initWithCapacity:0]
Is there a performance or memory penalty/difference?
This will create a mutable array and allocate memory that is enough to hold specified number of elements, so it can by any high enough number depending on implementation.
Is optimized to return an instance of __NSArray0 class which is the same instance each time you create it, so there's no extra memory allocations in this case.
So using
@[]
is more optimal, however you probably won't see real difference unless you call this function very frequently.Running some benchmarks in iOS simulator: