分配和释放VS。自动释放。为什么以及何时?

发布于 2024-10-26 08:44:27 字数 258 浏览 1 评论 0原文

我看到很多人都在分配和释放 NSString。

我知道这样做的好处是字符串会立即释放,而不是通过 autoRelease 释放。

我的问题:

  1. 它有效吗?我应该总是更喜欢在 autoRelease 上分配和释放吗?
  2. 更广泛的是-立即分配和释放,然后再次分配在dealloc中分配、使用和释放。

将不胜感激任何解释。

谢谢沙尼

I see that many people are allocating and releasing NSStrings.

I understand that the benefit is that the string is being released immediately and not by autoRelease.

my questions :

  1. does it effective and should i always prefer allocating and releasing on autoRelease?
  2. what is more expansive - allocating and releasing immediately and then allocating again OR allocating, using and releasing in dealloc.

will appreciate any explanation.

Thanks

shani

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

清泪尽 2024-11-02 08:44:27
  1. 大多数情况下这并不重要。我认为你应该使用 autorelease,因为它使代码更简单,而且 @"string" 快捷方式非常优雅。
  2. 基本区别在于发布发生的时间点。就像我说的,在大多数情况下,这没有任何区别。如果你想更严格地控​​制释放时间,那么你也可以通过滚动你自己的 NSAutoreleasePool 池来实现自动释放。
  1. In most cases it does not matter. I think you should use the autorelease since it makes the code more simple and the @"string" shortcut is very elegant.
  2. The basic difference is the point in time when the release happens. Like I said, in most cases it does not make any difference. If you want to control the release time more closely, then you can also do that for autorelease by rolling your own NSAutoreleasePool pool.
七禾 2024-11-02 08:44:27

我不明白如何重用 NSString。重用 NSMutableString 实例可能比重新创建它稍快一些,但您不会看到差异。专注于代码的简单性和可维护性。

我认为你的问题是使用 [[NSString alloc] init] 还是 [NSString string]。只要性能不是问题,就始终选择最简单的。这将是自动发布的版本,因为您不需要自己发布它。

I don't see how you could re-use a NSString. Reusing a NSMutableString instance might be slightly faster the recreating it but you won't see the difference. Focus on simplicity and maintainability of your code.

I think your question is wether to use [[NSString alloc] init] or [NSString string]. As long as performance is not an issue, always go with the simplest one. That would be the autoreleased version, because you don't need to release it yourself.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文