doubi2014
2017-01-02 08:09
浏览 43
已采纳

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.

图片转代码服务由CSDN问答提供 功能建议

Go语言源代码中的这种简短方法带有注释,表明它没有以最佳方式分配内存。

\ n

...在这里可以更好地进行分配...

Join 方法的源代码。 < p>什么是效率低下的分配? 我看不到分配源字符串片和目标字节片的方法。 源是密钥片。 目标是字节片。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dqiz20794 2017-01-02 10:04
    已采纳

    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)
    
    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题