The code referenced by the comment is memory efficient as written. Any allocations are in strings.Join
which is written to minimize memory allocations.
I suspect that the comment was accidentally copied and pasted from this code in the net/http package:
// TODO: could do better allocation-wise here, but trailers are rare,
// so being lazy for now.
if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"
"); err != nil {
return err
}
This snippet has the following possible allocations:
A more memory efficient approach is to allocate a single []byte
for the data to be written.
n := len("Trailer: ") + len("
")
for _, s := range keys {
n += len(s) + 1
}
p := make([]byte, 0, n-1) // subtract 1 for len(keys) - 1 commas
p = append(p, "Trailer: "...)
for i, s := range keys {
if i > 0 {
p = append(p, ',')
}
p = append(p, s...)
}
p = append(p, "
"...)
w.Write(p)