[swift-evolution] Pitch: @autoreleasepool attribute for loops
Charles Srstka
cocoadev at charlessoft.com
Fri Jan 8 19:32:48 CST 2016
When dealing with Objective-C code, especially older code that predates ARC, much of which can be found in standard Apple frameworks such as Foundation and AppKit, one is sure to generate a lot of autoreleased objects. In cases where a lot of autoreleased objects are generated inside a loop, this can lead to excessive memory usage unless one puts the body of the loop inside an autorelease pool. Traditionally, this would have been done in Objective-C like so:
for id foo in bar @autoreleasepool {
…
}
The Swift equivalent of this would be:
for foo in bar {
autoreleasepool {
…
}
}
However, due to Swift’s “autoreleasepool” function being implemented via a closure, this introduces a new scope, causing many forms of flow control not to work. Most problematically, the ‘break’ and ‘continue’ statements no longer function, since the control flow is no longer considered to be inside a loop, but there are other consequences too, such as not being able to early-return out of the method, or throw an error. The latter issue can be solved by writing a custom version of the “autoreleasepool” function that takes a throwing closure and rethrows it, but I can’t think of any workaround for the lack of “break” and “continue” with the current system other than breaking up the loop body into lots of smaller autoreleasepool statements.
I propose adding an @autoreleasepool attribute that could be added to loops, like so:
@autoreleasepool for foo in bar {
...
}
This would wrap the loop body inside an autorelease pool, without disabling the usual flow control statements.
What do you think?
Charles
More information about the swift-evolution
mailing list