[swift-evolution] Pitch: @autoreleasepool attribute for loops

Jacob Bandes-Storch jtbandes at gmail.com
Sat Jan 9 00:00:40 CST 2016


I sympathize with the problem statement, but I wonder if we should instead
be considering ways of allowing control-flow statements (break, continue,
return) to work from inside @noescape closures.

Another possible solution would be to expose __pushAutoreleasePool() and
__popAutoreleasePool() as public API. This would also allow more careful
manual use of autorelease pools (for instance, draining the pool after
every 5 loop iterations, rather than every iteration).

Jacob

On Fri, Jan 8, 2016 at 5:32 PM, Charles Srstka via swift-evolution <
swift-evolution at swift.org> wrote:

> 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
>
> _______________________________________________
> swift-evolution mailing list
> swift-evolution at swift.org
> https://lists.swift.org/mailman/listinfo/swift-evolution
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160108/3ec222a9/attachment.html>


More information about the swift-evolution mailing list