Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the cost of using autorelease in Cocoa?

Most of Apples documentation seems to avoid using autoreleased objects especially when creating gui views, but I want to know what the cost of using autoreleased objects is?

UIScrollView *timeline = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 20, 320, 34)];
[self addSubview:timeline];
[timeline release];

Ultimately should I use a strategy where everything is autoreleased and using retain/release should be the exception to the rule for specific cases? Or should I generally be using retain/release with autorelease being the exception for returned objects from convenience methods like [NSString stringWithEtc...] ?

like image 981
seanalltogether Avatar asked Oct 10 '08 23:10

seanalltogether


1 Answers

There are two costs:

  1. (Assuming you have an option to avoid autoreleased objects.) You effectively unnecessarily extend the lifetime of your objects. This can mean that your memory footprint grows -- unnecessarily. On a constrained platform, this can mean that your application is terminated if it exceeds a limit. Even if you don't exceed a limit, it may cause your system to start swapping, which is very inefficient.

  2. The additional overhead of finding the current autorelease pool, adding the autoreleased object to it, and then releasing the object at the end (an extra method call). This may not be a large overhead, but it can add up.

Best practice on any platform is to try to avoid autorelease if you can.

To answer the questions:

Ultimately should I use a strategy where everything is autoreleased and using retain/release should be the exception to the rule for specific cases?

Quite the opposite.

Or should I generally be using retain/release with autorelease being the exception for returned objects from convenience methods like [NSString stringWithEtc...] ?

You should always use retain/release if you can -- in the case of NSString there is typically no need to use stringWithEtc methods as there are initWithEtc equivalents.

See also this question.

like image 198
mmalc Avatar answered Dec 12 '22 07:12

mmalc