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

报告相同问题?

悬赏问题

  • ¥20 access中怎么分割分别获取一下图中的值
  • ¥15 类图中关联与聚合的区别
  • ¥15 ENVI高分五号去除云层的方法
  • ¥15 16进制数据如何得到奇偶校验位
  • ¥15 求合并两个字节流VB6代码
  • ¥15 Pyqt 如何正确的关掉Qthread,并且释放其中的锁?
  • ¥30 网站服务器通过node.js部署了一个项目!前端访问失败
  • ¥15 WPS访问权限不足怎么解决
  • ¥15 java幂等控制问题
  • ¥15 海湾GST-DJ-N500