What is the cost of using autorelease in Cocoa?

前端 未结 11 1518
眼角桃花
眼角桃花 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:45

    One side note to keep in mind is if you are spawning a new thread, you must setup a new Autorelease pool on that thread before you do anything else. Even if you are not using autorelease objects, chances are that something in the Cocoa APIs is.

    0 讨论(0)
  • 2020-11-30 08:47

    As I understand it, the main downside to using autorelease is that you don't know when the object will finally be released and destroyed. This could potentially cause your app to use a lot more memory than it needs to if you have a lot of autoreleased objects hanging around but not yet released.

    0 讨论(0)
  • 2020-11-30 08:49

    I have to disagree with Jim Puls - I think that not using Autorelease makes debugging more difficult, because you are more likely to find yourself accidentally leaking memory. Of course Clang static analyzer can pick up some of these instances, but for me, the slight overhead costs in habitually using autorelease are far overshadowed by my code being less likely to be buggy.

    And then, only if I have a tight loop I need to optimize will I start looking at performance. Otherwise this is all just premature optimization, which is generally considered to be a bad thing.

    0 讨论(0)
  • 2020-11-30 08:49

    Others have answered whether you should autorelease, but when you must autorelease, drain early and drain often: http://www.mikeash.com/?page=pyblog/autorelease-is-fast.html

    0 讨论(0)
  • 2020-11-30 08:50

    One benefit to using autorelease pools is that they are exception safe without using @try/@finally. Greg Parker ('Mr. Objective-C') has a great post explaining the details of this.

    I tend to use autorelease a lot as its less code and makes it more readable, IMO. The downside, as others have pointed out, is that you extend the lifetime of objects, thus temporarily using more memory. In practice, I have yet to find overuse of autorelease to be a significant issue in any Mac app I've written. If high memory usage does seem to be an issue (that isn't caused by a genuine leak), I just add in more autorelease pools (after profiling to show me where I need them). But, in general, this is quite rare. As Mike Ash's post shows (Graham Lee linked to it), autorelease pools have very little overhead and are fast. There's almost zero cost to adding more autorelease pools.

    Granted, this is all for Mac apps. In iPhone apps, where memory is more tight, you may want to be conservative in your use of autorelease. But as always, write readable code first, and then optimize later, by measuring where the slow/memory intensive parts are.

    0 讨论(0)
提交回复
热议问题