Why does this Swift code leak memory, and how do I handle it?

╄→尐↘猪︶ㄣ 提交于 2019-12-24 14:37:50

问题


This Swift code (based on another post here on Stack Overflow) computes ten million MD5 hashes (and does nothing with them, for the sake of this example). But the md5() function leaks memory; the longer it runs, the more memory it consumes:

import Foundation

func md5(string: String) -> [UInt8] {
    var digest = [UInt8](count: Int(CC_MD5_DIGEST_LENGTH), repeatedValue: 0)
    if let data = string.dataUsingEncoding(NSUTF8StringEncoding) {
        CC_MD5(data.bytes, CC_LONG(data.length), &digest)
    }
    return digest
}

for var i = 0; i < 10000000; i++ {
    let hash = md5(String(format:"%u", i))
}

What is it about this md5() function that's consuming memory and not freeing it automatically? Is there anything I can/should do in code to cause it to free memory it no longer needs?


回答1:


Probably the md5 function is creating autoreleased objects. Try this:

for var i = 0; i < 10000000; i++ {
    autoreleasepool {
        let hash = md5(String(format:"%u", i))
    }
}


来源:https://stackoverflow.com/questions/34102189/why-does-this-swift-code-leak-memory-and-how-do-i-handle-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!