dssnh86244 2017-08-04 14:36 采纳率: 100%
浏览 29
已采纳

释放未使用的内存?

I'm using the following function for downloading files smaller than 20MB. It read the entire content to memory as another function has to perform work on the bytes before it can be written to disk.

func getURL(url string) ([]byte, error) {
    resp, err := http.Get(url)
        if err != nil {
            return nil, fmt.Errorf("getURL: %s", err)
    }
    defer resp.Body.Close()

    body, err := ioutil.ReadAll(resp.Body)
    if err != nil {
            return nil, fmt.Errorf("getURL: %s", err)
    }

    return body, nil
}

This works fine, but all memory is consumed on the system.

Is it possible to release memory used by body after it has been processed by another function, so memory use won't be larger than the bytes currently being processed?

  • 写回答

1条回答 默认 最新

  • doulu1544 2017-08-04 14:42
    关注

    First I recommend to read the following questions / answers:

    FreeOSMemory() in production

    Golang - Cannot free memory once occupied by bytes.Buffer

    You may trigger a gc to free unused objects with runtime.GC() and you may urge your Go runtime to release memory back to OS with debug.FreeOSMemory(), but all these are just fire fighting. A well-written Go app should never have to call these.

    What you should do is prevent the runtime having to allocate large amount of memory.

    How may you achieve this? Some means (you can even combine these solutions):

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 MATLAB动图问题
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名