在Swift的循环中减少内存使用

Chr*_*ton 1 swift

我在Swift中有一个while循环,试图解决问题,有点像比特币挖矿。简化版本是-

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!
}
Run Code Online (Sandbox Code Playgroud)

尽管此循环正在运行,但内存使用量有时会稳定达到300mb,一旦完成,它似乎就不会释放。

有人能够解释为什么会这样吗,如果这是我应该担心的事情?

vac*_*ama 6

我怀疑您的问题是,您正在创建大量Strings,直到您的例程结束并且autoreleasepool被清空后才释放它们。尝试包装您的内部循环autoreleasepool { }以更早释放这些值:

while (hash > difficulty) {
    autoreleasepool {
        nonce = arc4random_uniform(range)
        hash = (root + String(describing: nonce)).sha256()
    }
}
Run Code Online (Sandbox Code Playgroud)