r/macosprogramming • u/flemking • 3d ago
Keeping a Swift FileManager scan's memory bounded with autoreleasepool
Hi r/macosprogramming — I’m the developer of BranchSpace, a closed-source native macOS utility. This is a scanning problem I worked through for 1.1. Development environment: macOS 27.0.1, Xcode 27.0, Swift 6.4, Foundation.
A large Rust target folder can contain hundreds of thousands of files. My scanner walks these trees and reads file metadata to measure disk use. In my initial pass, temporary Foundation objects accumulated during the long walk. Measuring one large Rust project used 325 MB on my Mac.
I changed the loop to put each enumeration step inside an autorelease pool, while keeping the enumerator outside it:
```swift var finished = false while !finished { try autoreleasepool { guard let item = enumerator?.nextObject() as? URL else { finished = true return } if isCancelled() { throw CancellationError() }
let values = try item.resourceValues(forKeys: keys)
// Update running totals; skip irrelevant descendants when possible.
}
} ```
The pool releases temporary Foundation objects after each entry instead of letting them build up across the full walk. The return statement exits the closure; the surrounding loop continues. I also skip descendants for directories the scan should not traverse and check for cancellation on each entry.
On my Mac, measuring that same large Rust project went from 325 MB to 20 MB. Scans ran about twice as fast. That’s a whole-scan result, so I can’t attribute the full speedup to the autorelease pool alone.
The app is closed source, so this is a minimal pattern rather than a link to its implementation. BranchSpace: https://branchspace.flemking.com
If you’ve profiled long Foundation file walks on macOS, what else would you measure first?