13

Possible Duplicate:
Is literal creation of an NSMutableDictionary less efficient than the class helper method?

According to the WWDC video that introduces ObjectiveC literals, NSMutableArrays can be initialized like so:

[NSMutableArray arrayWithArray:@[]];

but what if we were to do it like this:

[@[] mutableCopy];

I know that one is initializing the array, and the other is just providing a shallow copy; thus the memory management is different. But if we are using ARC, what are the disadvantages of using the latter? Is it more expensive? ARC probably handles both differently, but I'm just wondering if using mutableCopy is 'worse' or not.

Community
  • 1
  • 1
KDaker
  • 5,899
  • 5
  • 31
  • 44

1 Answers1

6

In the former case, you end up with two objects added to the current autorelease pool: the NSArray literal and the NSMutableArray that you’re creating from it. In the latter, the literal NSArray gets added to the autorelease pool but the NSMutableArray copied from it does not. So the first case is slightly worse, performance-wise, in that draining the autorelease pool (e.g. at the end of the run-loop cycle) requires releasing both objects in succession, while in the second case the copy will get released separately from the autoreleased literal. In practice, the time difference will be infinitesimal.

Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
  • interesting! that explains alot. thanks. – KDaker Sep 28 '12 at 17:15
  • 5
    Under ARC, unneeded autoreleases are often optimized out, so even that likely isn't a major concern. – Rob Napier Sep 28 '12 at 17:32
  • That isn't necessarily the case. The last time I tested, Foundation didn't appear to be compiled with ARC. This is important, because when compiling with ARC, clang doesn't insert `return [retVal autorelease];` - it actually inserts `return objc_autoreleaseReturnValue(retVal);`. Likewise, the caller (your code) doesn't call `-retain` on the result, it calls `objc_retainAutoreleasedReturnValue`. The combination of these two functions around that method return results in the object never actually entering the autorelease pool. Otherwise, it still ends up there. – Sterling Archer Jan 24 '13 at 18:39