gpt4 book ai didi

swift - 在 Swift 中减少循环期间的内存使用

转载 作者:搜寻专家 更新时间:2023-11-01 05:55:06 25 4
gpt4 key购买 nike

我在 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()
}
}

关于swift - 在 Swift 中减少循环期间的内存使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50668015/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com