What is the cost of using autorelease in Cocoa?

前端 未结 11 1542
眼角桃花
眼角桃花 2020-11-30 08:19

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?

11条回答
  •  遥遥无期
    2020-11-30 08:36

    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.

提交回复
热议问题