Cheok Yan Cheng
Cheok Yan Cheng

Reputation: 42690

How can we decide whether we should use autoreleasepool?

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

https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html#//apple_ref/doc/uid/20000047-1041876

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://stackoverflow.com/a/42935601/72437

Upvotes: 0

Views: 398

Answers (1)

Turtleeeeee
Turtleeeeee

Reputation: 179

Use FileManager to copy item doesn't have a huge payload. And Image I/O you're using will save a lot of memory during the I/O process. In addition, apple's image api will have caches for the same file.

That's why your code won't have a significant difference. Because you didn't make any memory payload.

You could try another way to validate the usage of autoreleasepool. And I can assure that it will have a tremendous difference.

Use for-loop(10000 times) to generate random strings (longer is better), and use each string to transform an UTF-8 data in each loop. Then see different memory growth from the with or without autoreleasepool case.

Try it out.

Upvotes: 1

Related Questions