go ``` cmd/compile:消除非整数n在切片扩展技术中的内存分配 ```

x6h2sr28  于 2个月前  发布在  Go
关注(0)|答案(5)|浏览(34)

#21266 中的切片扩展惯用法在 go tip 中不适用于非整数 nappend(a, make([]T, n)...) 中:

func BenchmarkExtendInt(b *testing.B) {
        var buf []byte
        b.ReportAllocs()
        n := int(12345)
        for i := 0; i < b.N; i++ {
                buf = append(buf[:0], make([]byte, n)...)
        }
}

func BenchmarkExtendUint64(b *testing.B) {
        var buf []byte
        b.ReportAllocs()
        n := uint64(12345)
        for i := 0; i < b.N; i++ {
                buf = append(buf[:0], make([]byte, n)...)
        }
}

基准测试结果:

BenchmarkExtendInt-4      	10000000	       145 ns/op	       0 B/op	       0 allocs/op
BenchmarkExtendUint64-4   	 1000000	      1576 ns/op	   13568 B/op	       1 allocs/op

如您所见,如果 n 的类型不是 int ,go 将不会删除分配。

ovfsdjhp

ovfsdjhp1#

我很好奇-像int16int64这样的其他整数类型会发生什么?

pvcm50d1

pvcm50d13#

在编写编译器优化时,这是一个已知的限制,并且在walk.go代码中有待办事项以支持更多类型。添加所有值适合int类型的类型应该不难。对于超出int值范围的类型,我们需要额外的运行时检查。例如,即使仅为了一致性,如果uint64值得支持,我们可以添加一个额外的检查,使其抛出与makeslice64相同的panic。一旦树开放go1.13,我会再看一下它。

xam8gpfp

xam8gpfp4#

https://golang.org/cl/182559提到了这个问题:cmd/compile: more optimization for append(x, make([]T, y)...) slice extension

q3qa4bjr

q3qa4bjr5#

https://golang.org/cl/182559修复了提供的基准测试。
这个问题是否可以关闭,或者这里还有其他事情要做吗?

相关问题