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.

  • 写回答

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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 求数学坐标画圆以及直线的算法
  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 自己瞎改改,结果现在又运行不了了
  • ¥15 链式存储应该如何解决
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站