减少 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!
}

当这个循环运行时,内存使用量有时会稳定达到~300mb,一旦完成,它似乎就不会被释放。

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

我怀疑您的问题是您正在创建大量String,直到您的例程结束并且自动发布池被清空,这些才会被释放。 尝试将内部循环包装在autoreleasepool { }中,以便更早地释放这些值:

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

最新更新