package main
import (
"testing"
)
type Wrap struct {
Stack []func(next Wrap)
One func(next Wrap)
}
func BenchmarkAllocates(b *testing.B) {
for i := 0; i < b.N; i++ {
x := Wrap{
Stack: []func(w Wrap){
func(w Wrap) {
},
}, // why does this allocate?
}
x.Stack[0](x)
}
}
func BenchmarkNoAllocate(b *testing.B) {
for i := 0; i < b.N; i++ {
x := Wrap{
One: func(w Wrap) {
},
}
x.One(x)
}
}
go test -benchmem
Why does BenchmarkNoAllocate cause memory to be allocated in the heap? Is there a way to avoid that but still pass a slice?
As far as I know both slice and func are pointer types, so I'd assume either both or neither to allocate.