1

To cut a long story short, here is a code snippet that would easily eat as much memory as it can until it's stopped. But why? When I wrap the scope inside while in autoreleasepool, not a single byte is leaked. However it affects only current scope; if there are leaky function calls, leakage will continue. So the answer is to just wrap leak-prone operations in autoreleasepool? It looks kinda ridiculous and non-swifty.

import Foundation

while true {
    let _ = "Foo Bar".data(using: .ascii)
    usleep(100)
}
Kirill Titov
  • 2,060
  • 5
  • 21
  • 33
  • Compare https://stackoverflow.com/questions/25860942/is-it-necessary-to-use-autoreleasepool-in-a-swift-program – Martin R Oct 16 '17 at 12:55

1 Answers1

0

This is not unexpected. Until your while returns control to the run loop, the top-level autorelease pool will not be drained. Objects put into it will continue to accumulate.

I'm a little surprised that ARC doesn't destroy the Data instances immediately, however, since assigning them to the "cut" means that they are in effect never in scope. There's no name by which you can ever refer to them, and no reason to keep them alive.

jscs
  • 63,694
  • 13
  • 151
  • 195
  • Here is another example of leaking Data, now without assigning to _: `func leak() { "Foo Bar".data(using: .ascii); }; while true { leak(); usleep(10); }` And this makes even less sense. – Kirill Titov Oct 16 '17 at 15:17
  • Same reasoning there; you're not dropping back to the run loop, so autoreleased objects are not cleaned up. See what happens if you run the `while` for some time, then leave it. – jscs Oct 16 '17 at 15:44