Better Programming

Advice for programmers.

Follow publication

Member-only story

What Is Autorelease Pool in Swift

And how to optimize memory usage in your loops

Zafar Ivaev
Better Programming
Published in
4 min readJan 17, 2022
Photo by Thomas Budge on Unsplash

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…

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Zafar Ivaev
Zafar Ivaev

Written by Zafar Ivaev

Senior iOS Engineer. I write about features of Swift and iOS development practices.

Responses (3)

Write a response