Skip to content

Instantly share code, notes, and snippets.

@bprosnitz
Created September 17, 2015 17:34
Show Gist options
  • Save bprosnitz/1ac875a686261fcda74e to your computer and use it in GitHub Desktop.
Save bprosnitz/1ac875a686261fcda74e to your computer and use it in GitHub Desktop.
Go method indirection benchmarks
package fs
// indirection techniques in go
//BenchmarkDirectFib-12 2000000000 0.13 ns/op
//BenchmarkSavePtr-12 30 34612496 ns/op
//BenchmarkUseBool-12 1000000000 0.53 ns/op
//BenchmarkIface-12 2000000000 0.16 ns/op
//ok fs 27.053s
import "testing"
type v struct {
}
func (x *v) fib(n int) int {
if n < 2 {
return n
}
return x.fib(n-1) + x.fib(n-2)
}
func BenchmarkDirectFib(b *testing.B) {
x := v{}
x.fib(38)
}
type q struct {
f func(n int) int
}
func (x *q) runfib(n int) int {
return x.f(n)
}
func (x *q) fib2(n int) int {
if n < 2 {
return n
}
return x.runfib(n-1) + x.runfib(n-2)
}
func BenchmarkSavePtr(b *testing.B) {
x := q{}
x.f = x.fib2
x.runfib(38)
}
type bb struct {
use bool
}
func (x *bb) runfib(n int) int {
if x.use {
return x.fib2(n)
} else {
return 5 * 4
}
}
func (x *bb) fib2(n int) int {
if n < 2 {
return n
}
return x.runfib(n-1) + x.runfib(n-2)
}
func BenchmarkUseBool(b *testing.B) {
x := bb{}
x.use = true
x.runfib(38)
}
type iimpl struct{}
func (x *iimpl) fib(iface i, n int) int {
if n < 2 {
return n
}
return iface.fib(iface, n-1) + iface.fib(iface, n-2)
}
type i interface {
fib(iface i, n int) int
}
func BenchmarkIface(b *testing.B) {
x := iimpl{}
x.fib(&x, 38)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment