2

I have a while loop in Swift that's attempting to solve a problem, a bit like Bitcoin mining. A simplified version is -

import SwiftyRSA

func solveProblem(data: String, complete: (UInt32, String) -> Void) {
    let root = data.sha256()
    let difficulty = "00001"
    let range: UInt32 = 10000000
    var hash: String = "9"
    var nonce: UInt32 = 0
    while (hash > difficulty) {
        nonce = arc4random_uniform(range)
        hash = (root + String(describing: nonce)).sha256()
    }
    complete(nonce, hash)
}

solveProblem(data: "MyData") { (nonce, hash) in
    // Problem solved!
}

Whilst this loop is running the memory usage will steadily clime sometimes reaching ~300mb, and once complete it doesn't seem to be released.

Would someone be able to explain why this is the case and if it's something I should be worrying about?

Chris Edgington
  • 2,937
  • 5
  • 23
  • 42

1 Answers1

11

I suspect your problem is that you are creating a large number of Strings that won't be freed until your routine ends and the autoreleasepool is emptied. Try wrapping your inner loop in autoreleasepool { } to free those values earlier:

while (hash > difficulty) {
    autoreleasepool {
        nonce = arc4random_uniform(range)
        hash = (root + String(describing: nonce)).sha256()
    }
}
vacawama
  • 150,663
  • 30
  • 266
  • 294
  • it may be frowned upon to ask, but could you advise on my memory question? I'd happily share the whole Xcode project: https://stackoverflow.com/questions/50668841/how-to-clear-memory-after-uiimageview-animationimages – RanLearns Jun 03 '18 at 17:32