Skip to content

Instantly share code, notes, and snippets.

@jakecoffman
Created December 9, 2017 19:59
Show Gist options
  • Save jakecoffman/9c3b388b678b7d7161d01fa8ab73cdbb to your computer and use it in GitHub Desktop.
Save jakecoffman/9c3b388b678b7d7161d01fa8ab73cdbb to your computer and use it in GitHub Desktop.
Go benchmark: concrete method call vs call through an interface
package bench
import "testing"
func Benchmark_InterfaceMethods(b *testing.B) {
s := &Struct{}
for n := 0; n < b.N; n++ {
s.Method()
}
}
func Benchmark_ConcreteMethods(b *testing.B) {
s := &Struct{}
var i Interface = s
for n := 0; n < b.N; n++ {
i.Method()
}
}
type Struct struct {
val uint
}
func (s *Struct) Method() {
s.val++
}
type Interface interface {
Method()
}
/*
Amazingly the call via an interface is faster (trivially).
goos: darwin
goarch: amd64
pkg: github.com/jakecoffman/tanklets/cmd/bench
Benchmark_InterfaceMethods-4 1000000000 2.01 ns/op
Benchmark_ConcreteMethods-4 1000000000 2.20 ns/op
PASS
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment