Freeing unused memory?

2019-01-28 21:41发布

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条回答
男人必须洒脱
2楼-- · 2019-01-28 22:04

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

查看更多
登录 后发表回答