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 put loop in @autoreleasepool.
1:
while ([rs next]) {
@autoreleasepool {
NSDictionary *dict = [self dictFromXX];
//...
}
}
2:
@autoreleasepool {
while ([rs next]) {
NSDictionary *dict = [self dictFromXX];
//...
}
}
Which is better? or any difference between code 1 and 2?
Thanks!
An autorelease pool stores objects that are sent a release message when the pool itself is drained. If you use Automatic Reference Counting (ARC), you cannot use autorelease pools directly. Instead, you use @autoreleasepool blocks.
An autorelease pool is actually a collection of objects that will be released at some point in the future (either at the end of the thread's run loop or at the end of the scope of an autorelease pool). When a pool is drained, all the objects in the pool at that time are sent the release message.
Memory management in swift is handled with ARC (= automatic reference counting). This means that active references to objects are counted and objects are released when they aren't referenced anymore.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With