Hi,
I have a feeling that line dump = append([]byte(fmt.Sprintf( ...
is not memory efficient because I don’t know the size of the byte, I use fmt
and cast string to byte.
How can I improve this please?
Thanks
dump, err := httputil.DumpResponse(res, true)
if err != nil {
return err
}
met := http.MethodGet
if res.request.Method != "" {
met = res.request.Method
}
uri := res.request.RequestURI
if uri == "" {
uri = res.request.URL.RequestURI()
}
dump = append([]byte(fmt.Sprintf("%s %s HTTP/%d.%d\nHost: %s\n",
met,
uri,
res.request.ProtoMajor,
res.request.ProtoMinor,
res.request.Host,
)), dump...)
In fact, the only variables whose lengths you don’t know are uri and host, both of which are generally less than 256.
So you can directly apply for a buffer of 512+len(dump) to solve most problems.
But this brings up a new problem. If you do nothing, append will only apply once when it encounters capacity expansion, which is not much different from the way you apply for memory in advance.
1.You may be worried about the efficiency of fmt, but it is a formatting tool that can help you format the output. If you are not pursuing extreme efficiency, optimizing fmt is not a good idea.
2.If you are concerned about the cost of converting string to byte, you can use unsafe.Pointer to convert. Similarly, if you are not pursuing extreme efficiency, it is not recommended to do it in such a cumbersome way.
To sum up, if you do not modify the byte slice later, the current method is a reasonable implementation.