In a Swift loop that imports thousands of images through Objective-C-backed APIs, why does memory climb until the loop ends, and how does autoreleasepool help?
answer
- a release postponed, not skipped
- Objective-C's deferred release
- who drains, and when
- one pool per iteration
basics
~20 sOn Apple platforms, Objective-C-backed objects can be autoreleased: a pool holds them until it drains, and the enclosing pool may not drain until the loop ends. Wrapping each iteration in autoreleasepool drains them every iteration, so peak memory stays flat.
solid answer
~50 sPure Swift code doesn't use the pool, but code that interoperates with Objective-C may put references in it: an Objective-C method that returns an object the caller does not own can autorelease it, and the pool keeps that strong reference until it drains. The enclosing pool drains only when control returns to whoever created it — on the main thread, the event loop — so a tight loop decoding thousands of images keeps every iteration's autoreleased temporaries alive until the loop finishes, and memory climbs even though your own references are long gone. `autoreleasepool(invoking:)`, from the `ObjectiveC` module, pushes a pool, runs the closure and pops the pool, releasing whatever that iteration autoreleased. Put it inside the loop body; one pool around the whole loop changes nothing. It cannot help with memory your own variables or arrays still hold.
code
swift · 20 linesimport Foundation
// Apple platforms only: autoreleasepool(invoking:) comes from the ObjectiveC module.
func importImages(at urls: [URL]) -> Int {
var headerBytes = 0
for url in urls {
autoreleasepool {
// Objective-C-backed objects created in this iteration that land in the
// autorelease pool are released when this closure returns.
guard let data = NSData(contentsOf: url) else { return }
let length = min(16, data.length)
let header = data.subdata(with: NSRange(location: 0, length: length))
headerBytes += header.count
}
}
return headerBytes
}
let dir = FileManager.default.temporaryDirectory
print(importImages(at: [dir.appendingPathComponent("missing.png")]))go deeper
Recall that on Apple platforms some objects wait in an autorelease pool, and that autoreleasepool inside a loop releases them each iteration.
Explain how autoreleased objects outlive your references until the pool drains, and why the pool must sit inside the loop body.
Tell autorelease build-up apart from objects your own code retains, using the shape of the memory graph over the loop, and fix the right one.
Decide where batch imports belong and how they bound memory, rather than sprinkling pools through code that never calls Objective-C.
## What the autorelease pool is **Autorelease** is an Objective-C mechanism for a deferred release. When an Objective-C method returns an object the caller does not own, it can send the object `autorelease`: the object is added to the current **autorelease pool**, which holds a strong reference to it until the pool **drains**. Pools nest; draining the innermost one releases everything added since it was pushed. Swift's own ARC does not need the pool — a Swift instance is released when its last strong reference goes. But the Swift project's testing guide notes that code which interoperates with Objective-C "may put references in the autorelease pool". On Apple platforms that includes many Foundation and framework calls that are implemented in Objective-C. Platforms without the Objective-C runtime have no autorelease pool to drain. ## Why a loop makes memory climb 1. Your code calls an Objective-C-backed API inside a loop — reading a file, decoding an image, producing a thumbnail. 2. Some objects returned or created along the way are autoreleased, so the enclosing pool holds a strong reference to each one. 3. Your own variables release their references at the end of each iteration, but the pool's references remain. 4. The enclosing pool drains only when control returns to whoever pushed it — for main-thread code, typically the event loop once it finishes handling the current event. 5. A loop over thousands of images never returns control, so every iteration's autoreleased objects stay alive until the loop ends: memory grows roughly with the number of iterations, then drops at once. ## The fix: a pool per iteration In the Swift 6.4 SDK the function is declared as `autoreleasepool<E, Result>(invoking body: () throws(E) -> Result) throws(E) -> Result`, with `Result: ~Copyable`. Its body pushes a pool, runs the closure and pops the pool in a `defer`, so the pool drains even when the body throws. ```swift for url in urls { autoreleasepool { // Objective-C-backed work for one image } } ``` - **Inside the loop body**, each iteration's autoreleased objects are released before the next iteration starts, so the peak stays near one iteration's worth. - **Around the whole loop**, one pool collects everything and drains at the end: the same peak as no pool. - The closure can return a value and throw — `let size = try autoreleasepool { try decode(url) }` — because the function is generic over the result and uses typed throws. - If pushing and popping a pool every iteration ever shows up in a profile, wrap batches of iterations instead; the peak grows to one batch's worth. ## When it does not help | Symptom | Cause | What fixes it | |---|---|---| | memory climbs during a loop of Objective-C-backed calls, then falls when it ends | autoreleased temporaries waiting for the pool to drain | `autoreleasepool` inside the loop body | | memory climbs and stays high after the loop | your own array or cache still holds the results | drop or bound those references | | instances never deinitialize at all | a strong reference cycle | break the cycle with `weak` or `unowned` | | a pure Swift loop with no Objective-C calls grows | live Swift references, not the pool | find who holds them; the pool releases nothing here | The pool only releases references **it** holds. It never frees an object that something else still references strongly, and it does not make ARC release ordinary Swift references any sooner. ## Telling the two apart Before adding a pool, look at the shape of memory over the loop: - a **ramp that falls back** as soon as the loop returns points at autoreleased temporaries — the enclosing pool drained when control came back to it; - a **ramp that stays** after the loop points at references your own code still holds, and a pool will not move it; - a **flat line with occasional spikes** inside each iteration is normal working memory for one image, which no pool reduces. Then make the smallest change that matches: a pool inside the loop body for the first, and dropping or bounding your own collection for the second. ## In an interview A strong answer names the mechanism — deferred release through the autorelease pool — places the pool **inside** the loop, and says when the tool is irrelevant: pure Swift code, platforms without the Objective-C runtime, and memory held by your own references.
- Does autoreleasepool make ARC release your Swift objects sooner?No. ARC already releases a Swift instance when its last strong reference goes; the pool only holds references that Objective-C code autoreleased. If memory stays high because an array keeps every decoded image, the pool changes nothing — drop or bound those references instead.
- Can the autoreleasepool closure return a value or throw?Yes. In the Swift 6.4 SDK it is `autoreleasepool(invoking:)`, generic over the result and using typed throws, so `let size = try autoreleasepool { try decode(url) }` compiles. The pool is popped in a `defer`, so it drains even when the closure throws.
The autorelease pool is the dish rack by the sink: dishes put there are cleared only when someone empties it. A pool per iteration is emptying the rack after every meal instead of at the end of a day-long banquet.
- ARC frees everything immediately, so a loop cannot build up memory
- autoreleasepool frees Swift objects that are still referenced
- One autoreleasepool around the whole loop lowers the peak
- Every Swift loop needs autoreleasepool to avoid leaks
- autoreleasepool can be called only from Objective-C code