Why use Autorelease pool?

前端 未结 1 1481
独厮守ぢ
独厮守ぢ 2020-12-24 02:08

I know there is an autorelease pool created in the main method and all the objects that receive autorelease message get stored in this pool and get released when the pool dr

相关标签:
1条回答
  • 2020-12-24 02:45

    Your assumption is correct. When you can ensure a specific thread is never making use of autoreleased objects, that thread wouldn't need an autorelease pool.

    Avoiding the autoreleasepool is a bad advice, the coin has two sides. Using autorelease'd objects carries a certain amount of overhead (although insignificant in most scenarios) that should be avoided when possible. Especially in cases where there are multiple exits to a method, or an exception can be encountered, autoreleasing helps avoiding memory leaks and makes code cleaner.

    Be aware though, that this means nothing on that thread can use autorelease, including any frameworks you may call. There are situations where this is the case, such as in a classic producer/consumer scenario. You have a producer that creates objects, dispatches them to the main threads runloop, and can register them in the main threads autoreleasepool consequently.

    In general, I would not recommend creating a thread where significant work is carried out (besides a simple, long running computation) without an autoreleasepool.

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