Skip to content

Instantly share code, notes, and snippets.

@mjard
Created December 12, 2012 20:30
Show Gist options
  • Save mjard/4271311 to your computer and use it in GitHub Desktop.
Save mjard/4271311 to your computer and use it in GitHub Desktop.
Benchmarking Go Interfaces
package main
import (
"testing"
)
func Nop() {
}
type Stupid interface {
Nop()
}
type Lame struct {
}
func (l Lame) Nop() {
}
func BenchmarkNop(b *testing.B) {
for i := 0; i < b.N; i++ {
Nop()
}
}
func BenchmarkMemberFunction(b *testing.B) {
a := Lame{}
for i := 0; i < b.N; i++ {
a.Nop()
}
}
func BenchmarkMemberFunctionWithStructPointer(b *testing.B) {
a := &Lame{}
for i := 0; i < b.N; i++ {
a.Nop()
}
}
func AcceptsStupid(s Stupid) {
s.Nop()
}
func BenchmarkInterfaceFunction(b *testing.B) {
a := Lame{}
for i := 0; i < b.N; i++ {
AcceptsStupid(a)
}
}
func BenchmarkInterfaceFunctionWithCast(b *testing.B) {
a := Lame{}
for i := 0; i < b.N; i++ {
AcceptsStupid(Stupid(a))
}
}
func BenchmarkInterfaceFunctionWithCastSaved(b *testing.B) {
a := Lame{}
c := Stupid(a)
for i := 0; i < b.N; i++ {
AcceptsStupid(c)
}
}
func BenchmarkInterfaceFunctionWithTypeAssert(b *testing.B) {
a := Lame{}
c := Stupid(a).(Stupid)
for i := 0; i < b.N; i++ {
c.Nop()
}
}
/*
---Results---
BenchmarkNop 2000000000 1.28 ns/op
BenchmarkMemberFunction 2000000000 1.92 ns/op
BenchmarkMemberFunctionWithStructPointer 2000000000 1.45 ns/op
BenchmarkInterfaceFunction 50000000 32.0 ns/op
BenchmarkInterfaceFunctionWithCast 50000000 32.0 ns/op
BenchmarkInterfaceFunctionWithCastSaved 100000000 12.7 ns/op
BenchmarkInterfaceFunctionWithTypeAssert 200000000 8.93 ns/op
ok local/temp/bench 17.034s
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment