golang:最佳排序和连接字符串

This short method in go's source code has a comment which implies that it's not allocating memory in an optimal way.

... could do better allocation-wise here ...

This is the source code for the Join method.

What exactly is inefficiently allocated here? I don't see a way around allocating the source string slice and the destination byte slice. The source being the slice of keys. The destination being the slice of bytes.

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)