reduce runtime.convT2I -> runtime.newobject -> runtime.mallocgc
conversion from value to interface is more expensive than
conversion from pointer to interface.
package main
import "testing"
type I interface {
String() string
}
type val struct {
s string
}
func (v val) String() string { return v.s }
type ptr struct {
s string
}
func (p *ptr) String() string { return p.s }
func BenchmarkT2IForValue(b *testing.B) {
var intf I
for i := 0; i < b.N; i++ {
intf = val{"abc"}
}
_ = intf
}
func BenchmarkT2IForPtr(b *testing.B) {
var intf I
for i := 0; i < b.N; i++ {
intf = &ptr{"abc"}
}
_ = intf
}
% go test -bench . a_test.go
testing: warning: no tests to run
PASS
BenchmarkT2IForValue 20000000 90.9 ns/op
BenchmarkT2IForPtr 20000000 76.8 ns/op
ok command-line-arguments 3.539s
9 files changed