在 Cocoa 中使用 autorelease 的成本是多少? [英] What is the cost of using autorelease in Cocoa?

查看:33
本文介绍了在 Cocoa 中使用 autorelease 的成本是多少?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数 Apple 文档似乎都避免使用自动释放对象,尤其是在创建 gui 视图时,但我想知道使用自动释放对象的成本是多少?

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];

最终我是否应该使用一种策略,其中一切都是自动发布的,并且使用保留/发布应该是特定情况下规则的例外?或者我通常应该使用保留/释放,而自动释放是从 [NSString stringWithEtc...] 等便利方法返回的对象的例外?

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...] ?

推荐答案

有两个成本:

  1. (假设您可以选择避免自动释放对象.)您实际上不必要地延长了对象的生命周期.这可能意味着您的内存占用增加 - 不必要的.在受限平台上,这可能意味着您的应用程序如果超过限制就会被终止.即使不超过限制,也可能导致您的系统开始交换,这是非常低效的.

  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.

查找当前自动释放池,将自动释放的对象添加到其中,然后在最后释放对象(额外的方法调用)的额外开销.这可能不是很大的开销,但可以加起来.

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.

回答问题:

最终我是否应该使用一种策略,所有内容都是自动发布的,并且使用保留/发布应该是特定情况下规则的例外?

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

恰恰相反.

或者我通常应该使用保留/释放,而自动释放是从 [NSString stringWithEtc...] 等便利方法返回的对象的例外?

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

如果可以,您应该总是使用保留/释放——在 NSString 的情况下,通常不需要使用 stringWithEtc 方法因为有 initWithEtc 等价物.

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.

另见 这个问题.

这篇关于在 Cocoa 中使用 autorelease 的成本是多少?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆