为什么此Swift代码会泄漏内存,我该如何处理呢? [英] Why does this Swift code leak memory, and how do I handle it?

查看:148
本文介绍了为什么此Swift代码会泄漏内存,我该如何处理呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个Swift代码(基于Stack Overflow上的另一篇文章)计算了1000万个MD5哈希值(对于本示例而言,它们不执行任何操作).但是md5()函数会泄漏内存;它运行的时间越长,消耗的内存就越多:

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))
}

此md5()函数正在消耗内存而不没有自动释放它的原因是什么?我可以/应该在代码中做些什么使它释放不再需要的内存?

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?

推荐答案

md5函数可能正在创建自动释放的对象.试试这个:

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))
    }
}

这篇关于为什么此Swift代码会泄漏内存,我该如何处理呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆