Since Apple's API is not opened source nor it is mentioned in the documentation, when writing in Swift, we have no way, to know whether the returned object is an autorelease
objective-c object.
Hence, it becomes unclear when we should use autoreleasepool
If you write a loop that creates many temporary objects.
You may use an autorelease pool block inside the loop to dispose of those objects before the next iteration. Using an autorelease pool block in the loop helps to reduce the maximum memory footprint of the application.
Without autoreleasepool
for ... {
FileManager.default.copyItem
CGImageSourceCreateWithURL
CGImageSourceCopyPropertiesAtIndex
CGImageSourceCreateThumbnailAtIndex
CGImageDestinationCreateWithURL
CGImageDestinationFinalize
}
With autoreleasepool
for ... {
autoreleasepool {
FileManager.default.copyItem
CGImageSourceCreateWithURL
CGImageSourceCopyPropertiesAtIndex
CGImageSourceCreateThumbnailAtIndex
CGImageDestinationCreateWithURL
CGImageDestinationFinalize
}
}
I try to run an intensive loop over the above 2 code for comparison purpose.
I found no significant difference in their memory usage pattern, based on XCode memory report.
I was wondering, what are some good guideline/ thought process, to decide whether we should apply autoreleasepool
throughout our code?
I have such concern, as recently I saw autoreleasepool
is required in code which involves FileHandle.read
- https://mcmap.net/q/653698/-swift-calculate-md5-checksum-for-large-files
autoreleasepool
if you are creating a large amount of large objects in a tight loop without giving control back to the event loop (which takes care of the auto-releasing). – Dodeautoreleasepool
? When you profile your app and see dramatic memory growth. E.g. #25861442. – DeirdredeismCreate
(orCopy
) in their name, see the Create Rule, which has nothing to do with autorelease objects. – Deirdredeism