Cleaning Memory Footprint with the Autoreleasepool in Swift

Oğuz Öztürk
Mediate Labs
Published in
2 min readJan 10, 2021

What is autoreleasepool and how can we use it? Let’s find out!

We can define “autoreleasepool” as a closure that ensures the relevant object will be deleted from the memory. Threads have their own release pools. Therefore, it’s not necessary to write an additional code to delete objects from memory. However, unless we specify, the objects created in the “for” loops are not deleted from the memory until the loop ends. In this case, it will be beneficial to add an “autoreleasepool” to the for loop to reduce the memory usage.

As an example, if we use the code above and compare it with the autoreleasepool in the project that contains only a picture (400kb size, sample), a memory usage difference will be seen as below:

If an application containing this code had run on a device with less than 2GB of memory, it would be crashed by the system since it uses excessive memory.

Note:

The example above is derived from a scenario where the files are written to FileManager, and the file paths are recorded in CoreData instead of saving the images directly to CoreData (See Example).

It would be appreciated if you can leave a comment under the article if you come across different real-life scenarios.

--

--