@autoreleasepool in loop or loop in @autoreleasepool?

前端 未结 6 582
遇见更好的自我
遇见更好的自我 2020-12-30 23:22

It\'s a good practice to put lots of autoreleased object in an autoreleasepool at loop action. I found someone put the @autoreleasepool in loop but others p

6条回答
  •  一向
    一向 (楼主)
    2020-12-30 23:57

    @autoreleasepool blocks are more efficient than using an instance of NSAutoreleasePool directly; you can also use them even if you do not use ARC. - NSAutoreleasePool Class Reference

    You generally do not need autorelease pools, if you do because you are in a loop and autoreleasing lots of objects then option 1 makes more sense than 2 as you are trying to avoid the spike that the loop is creating. The time to use option 2 is if there isn't an autorelease pool set up (if you are performing a selector in the background for example or in +load), but you should really try to use GCD for those anyway.

    In summary, if you do not have a very long method and you need to wrap a loop in a autorelease pool, go for option 1 in most cases. If the method is being called without an autorelease pool having been set up then @autorelease needs to be the first thing.

提交回复
热议问题