Autorelease vs. release
Asked Answered
A

1

5

When I need an array for temporary use, what's the difference between these:

1:

NSMutableArray *stuff = [[NSMutableArray alloc] init];
// use the array
[stuff release];

2:

NSMutableArray *stuff = [NSMutableArray array];
// use the array

3:

NSMutableArray *stuff = [[[NSMutableArray alloc] init] autorelease];
// use the array

I prefer number 2, since it's shorter. Are there any good reasons to use number 1 or 3?

Anachronistic answered 2/11, 2010 at 11:27 Comment(0)
E
10

Number 2 is likely the best choice in most cases.

Number 1 has the chance of losing the release at some point down the line, for whatever reason, but it does release the array immediately, which in memory-starved environments can be useful.

Number 3 is basically a verbose equivalent of number 2, but it does come in handy if you want to use an initWith* that doesn't have a corresponding arrayWith*.

Note: If you are memory-starved, such as in an expensive loop where you need a fresh array for each iteration; don't release and allocate new arrays; just use -removeAllObjects and recycle the array.

Exposure answered 2/11, 2010 at 11:30 Comment(4)
Thanks! Good point about the immediate release of memory in number 1.Anachronistic
On the iPhone, you'll find most people use number 1 because the memory gets given back to the runtime sooner. In fact, Apple recommend avoiding autorelease as much as possible (on the iPhone).Scalpel
Good answer, save for the last bit. I'd wager that the difference between creating a new array on each pass and removing all objects is immeasurable and, quite likely, removing all objects will be trivially slower. In any case, don't optimize until you have a quantified performance problem.Cowley
@bburn: How could removing all objects be slower than releasing the array; as the former is a part of the process for the latter?Exposure

© 2022 - 2024 — McMap. All rights reserved.