背景
之前提交了一个功能,维护者后将一部分代码优化成如此,印象中返回具体类型性能会更好,想验证为什么需要返回使用指针。
研究
直接上代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
| package slices
import ( "sync" "testing" )
const appendN = 1000
var optPool = sync.Pool{ New: func() any { ints := make([]int, 0, appendN) return &ints }, }
func BenchmarkAppendWithPool(b *testing.B) { b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { sl := optPool.Get().(*[]int) for j := 0; j < appendN; j++ { *sl = append(*sl, j) } *sl = (*sl)[:0] optPool.Put(sl) } }
var optPool2 = sync.Pool{ New: func() any { return make([]int, 0, appendN) }, }
func BenchmarkAppendWithPool2(b *testing.B) { b.ResetTimer() b.ReportAllocs() for i := 0; i < b.N; i++ { sl := optPool2.Get().([]int) for j := 0; j < appendN; j++ { sl = append(sl, j) } sl = sl[:0] optPool2.Put(sl) } }
|
基准测试结果: