1 回答
TA贡献1876条经验 获得超7个赞
尝试使用颠覆编译器只会使转义分析更难完成其工作,从而阻止切片被堆栈分配。只需分配单个切片,并在每次循环迭代中重复使用它:unsafe.Pointer
func build(res [][]int, targets []int) {
buff := make([]int, 0, 6)
step := len(res) / len(targets)
for i := range targets {
buff = buff[:0]
for j := i * step; j < (i+1)*step; j++ {
res[j] = append(res[j], targets[i])
}
if len(targets) != 1 {
buff = append(buff, targets[:i]...)
buff = append(buff, targets[i+1:]...)
build(res[i*step:(i+1)*step], buff)
}
}
return
}
这可以通过编译器正确优化
./main.go:26:17: make([]int, 0, 6) does not escape
并且只会导致所需的分配:
Benchmark-8 44607 26838 ns/op 52992 B/op 721 allocs/op
- 1 回答
- 0 关注
- 93 浏览
添加回答
举报