What is the cost of using autorelease in Cocoa?

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.

Leave a Comment