Member-only story
What Is Autorelease Pool in Swift
And how to optimize memory usage in your loops
In this article, we will learn about autoreleasepool
in Swift and how it can help us optimize memory usage in loops. The source code of the project you will find at the end of the tutorial. This is what you will learn:
- What is an autorelease pool
- How it works under the hood
- When and how to use it in Swift codebase
- How it is used in Objective-C (useful to know since the question is sometimes asked in technical interviews)
Without further ado, let’s get started.
Let’s Start
Before we define autorelease pool, we need to know how reference counting works. When a reference is created, the retain
command is executed, which keeps the object alive. To decrement the reference count, and, potentially remove the object from memory when the count is equal to 0, the release
command is run. The Automatic Reference Counting (ARC) takes care of this for us.
NSAutoreleasePool
is a storage for objects that get sent release
commands when the pool is drained. The pool retains those objects till the drain
method is called, which happens when we return from the context that created that pool. For example, when we have an…