1

I have looked at many posts on the internet and can not find an answer satisfying me. They all said that Autorelease pool is used to avoid the peek in memory when we creating too many temporary objects. And they gave the example like this one:

for _ in 1...5 {
  autoreleasepool {
    let dog = Dog() //Dog is just a simple class
  }
}

Then I have done a simple experiment to understand it better:

class Dog {
  init() {
    print("Dog inited")
  }
  deinit {
    print("Dog deinited")
  }
}

//And then in main controller we call:
for _ in 1...5 {
  let _ = Dog()
}
print("End of loop")

Here is the output:

Dog inited
Dog deinited
Dog inited
Dog deinited
Dog inited
Dog deinited
Dog inited
Dog deinited
Dog inited
Dog deinited
End of loop

From what I understand, when we get out of the 1st loop, the first dog object should be released immediately. And then, we go to the second loop, the 2nd dog will be initialized and so on. Basically, we will never run into the situation where all the temporary objects remaining in the memory, right? Then, what is the point of Autorelease pool?

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
Vuong Cuong
  • 192
  • 9
  • 3
    Without the Auto Release Pool, it's more "release when possible what's in the scope". With the Auto Release Pool, it's more: "release when scope is done". Your objects won't be available outside they scope, but memory might not have been really freed yet. That's with big computation (like imagery), you need one. – Larme Nov 22 '18 at 10:56
  • @Larme Could you give an example or a block of code to clearly see the difference between use and not use the pool? – Vuong Cuong Nov 22 '18 at 11:02
  • 4
    https://stackoverflow.com/questions/25860942/is-it-necessary-to-use-autoreleasepool-in-a-swift-program ? Doing it everywhere is premature optimization. You just need to check the memory usage, and know if you'll take memory and prevent issue. It's an old question, Swift 1 maybe, but the logic should remain the same. – Larme Nov 22 '18 at 11:05
  • Great. Thanks for your explanation! – Vuong Cuong Nov 22 '18 at 11:08

0 Answers0