Objective-C: What's the difference between @[ ] and [[NSArray alloc] initWithCapacity:0]

167 Views Asked by At

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?

1

There are 1 best solutions below

1
On
[[NSMutableArray alloc] initWithCapacity:0]

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:

NSLog(@"%llu", dispatch_benchmark(100, ^{
    for (int i = 0; i < 1000000; ++i) {
      NSArray *a = @[];
    }
  }));

NSLog(@"%llu", dispatch_benchmark(100, ^{
    for (int i = 0; i < 1000000; ++i) {
      NSArray *a = [[NSMutableArray alloc] initWithCapacity:0];
    }
  }));


 Array Literal: 9835575 ns
 Mutable Array: 157169503 ns