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

golang: optimal sorting and joining strings

This short 方法在 go 的源代码中有一个注释,暗示它没有以最佳方式分配内存。

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

ThisJoin 方法的源代码。

这里分配的效率低下到底是什么?我看不到分配源字符串切片和目标字节切片的方法。源是键的切片。目的地是字节片。

code referenced by the comment 是写的内存效率。任何分配都在 strings.Join 中,这是为了最小化内存分配而编写的。

我怀疑评论是不小心从这里复制粘贴的 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, ",")+"\r\n"); err != nil {
            return err
        }

此代码段具有以下可能的分配:

一种更有效的内存方法是为要写入的数据分配一个 []byte

n := len("Trailer: ") + len("\r\n")
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, "\r\n"...)
w.Write(p)