Skip to content

Instantly share code, notes, and snippets.

@rprtr258
Last active May 7, 2023 00:09
Show Gist options
  • Save rprtr258/76446ce5bbd6b4e04244f0124b8bf955 to your computer and use it in GitHub Desktop.
Save rprtr258/76446ce5bbd6b4e04244f0124b8bf955 to your computer and use it in GitHub Desktop.
direct call/interface/function pointer benchmark
package tt
/*
goos: linux
goarch: amd64
cpu: Intel(R) Core(TM) i3-6100U CPU @ 2.30GHz
BenchmarkInterface-4 402143721 2.880 ns/op
BenchmarkTemplate-4 205737126 6.119 ns/op
BenchmarkDirect-4 1000000000 0.5869 ns/op
BenchmarkFunctionPointer-4 166973348 6.738 ns/op
BenchmarkFunctionPointerStruct-4 185710765 6.038 ns/op
PASS
ok command-line-arguments 8.509s
*/
import "testing"
type I interface {
f()
}
type S struct{}
func (S) f() {}
func BenchmarkInterface(b *testing.B) {
var s I = S{}
for i := 0; i < b.N; i++ {
s.f()
}
}
func f[S I](s S) {
s.f()
}
func BenchmarkTemplate(b *testing.B) {
s := S{}
for i := 0; i < b.N; i++ {
f(s)
}
}
func BenchmarkDirect(b *testing.B) {
s := S{}
for i := 0; i < b.N; i++ {
s.f()
}
}
func BenchmarkFunctionPointer(b *testing.B) {
s := S{}
f := s.f
for i := 0; i < b.N; i++ {
f()
}
}
type F struct {
f func()
}
func BenchmarkFunctionPointerStruct(b *testing.B) {
s := S{}
f := F{f: s.f}
for i := 0; i < b.N; i++ {
f.f()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment