I am wondering if there’s any benefit of using @autoreleasepool on an ARC code inside a method.
I mean this. Suppose I have a memory intensive method that is called several times in sequence. Something like
// this is my code
for (id oneObject in objects {
[self letsUseMemory];
}
and then
- (void) letsUseMemory {
// heavy use of memory here
}
and I do this
- (void) letsUseMemory {
@autoreleasepool {
// heavy use of memory here
}
}
Is there any benefit? I mean, the method variables will be deallocated anyway when the method finishes, so adding an autoreleasepool there, in theory, will do any benefit, right?
Or will autoreleasepool inside that method speed the deallocation?
thanks.
It depends. Any autoreleased temporary objects will not be deallocated until the pool drains, regardless of whether you’re using ARC. I.e.:
Without an enclosing @autoreleasepool, that object instance may hang around until you return to the run-loop. If that line of code exists within a loop, you may be accumulating a large number of these temporary objects.
The general rule of thumb is that if you have a potentially large loop that may create autoreleased objects, wrap the inside of the loop in with an @autoreleasepool.
It’s less common and perhaps somewhat meaningless to wrap a single method in an @autoreleasepool because it would usually only have meaningful effect if the method was called many times in a loop. Putting the @autorelease pool in the loop makes the intent more clear.