I am triying to grasp how reminiscence is dealt with in iOS. That is derived from the confusion of when to make use of autoreleasepool.
I attempted the instance of getting a operate the place I run a protracted for-loop and instantiate inside it a heavy object. Instance right here:
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
if indexPath.merchandise == 0 {
for i in 0..<5000000 {
let string = UIView(body: CGRect.zero)
}
} else {
for i in 0..<5000000 {
autoreleasepool {
let string = UIView(body: CGRect.zero)
}
}
}
(The gathering view is simply so I can simply click on a group view cell and set off the code).
So I observed that the model the place I dont use autoreleasepool
the reminiscence utilization is 1.69GB
and within the model once I do use autoreleasepool
the reminiscence is de facto related (typically even increased than with out the autoreleasepool block).
In order that’s my first query, how is helpful autoreleasepool
? I’ve seen different questions right here in stackoverflow traying to elucidate that:
- In case you write a loop that creates many short-term objects. Chances are you’ll create an autorelease pool contained in the loop to get rid of these objects earlier than the subsequent iteration. Utilizing an autorelease pool within the loop helps to scale back the utmost reminiscence footprint of the appliance.
However I noticed one other rationalization saying that objects created in native variables outlined inside for-loops are deallocated after the top of each iteration, and you do not want autorelease
block.
So unsure what is the appropriate performance right here.
Additionally, I believed that object are routinely deallocated when there are 0 robust references pointing to it, is that this appropriate? or not?
If not, when are these really deallocated within the system?
How native variables work inside a operate?Are they saved alive till the operate finishes?
How is the stack and the heap concerned right here?