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?