Created
December 9, 2017 19:59
-
-
Save jakecoffman/9c3b388b678b7d7161d01fa8ab73cdbb to your computer and use it in GitHub Desktop.
Go benchmark: concrete method call vs call through an interface
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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