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
Here is a different approach with Core Data an autoreleasepools:
Testing Core Data with very big hierarchical data sets of Efficiently Importing Data
important for you is the Wrap the contents of the outer loop in an NSAutoreleasePool init/release and NSManagedObjectContext save
solution.
In your first example for every iteration the pool is drained. This makes sense if the body of the iteration involves a lot of autoreleased objects.
The second example will only drain the pool once after the loop.
So if the internals of the loop are causing the memory bloat then go for option one. If the memory bloat over the whole loop is acceptable then loop then use option two.
In the first example autoreleasepool is created at the beginning of iteration and is drained and the end of iteration. In the second case pool is created once and is destroyed only after the loop is finished. If you use the second variation then you can get a big memory overhead since all autoreleased objects are freed only at the end. However you should consider the amount of data you need to process. In most cases the second variant is more preferred.
I would go for version 2.
A @autoreleasepool
block will release all objects that received a autorelease
when the block was finished. This will take time because it will need some cpu cycles and depending on the object, the used time can be much higher then expected.
I think custom @autoreleasepool
s only make sense when working with many data > 20MB or working with Data in a non-main-thread.
So. I recommend to avoid "short" @autoreleasepool
's. Because it may slow down your execution.
@autoreleasepool
blocks are more efficient than using an instance ofNSAutoreleasePool
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.
Depend on how many pending items will be released. Image that Autorelease Pool like your trash, put unused thing and will throw later.