Skip to content

Instantly share code, notes, and snippets.

@deadblue
Created January 10, 2021 15:06
Show Gist options
  • Save deadblue/b232340144acd20f48d38602fd628a1b to your computer and use it in GitHub Desktop.
Save deadblue/b232340144acd20f48d38602fd628a1b to your computer and use it in GitHub Desktop.
package ghost
import (
"reflect"
"testing"
)
type BarFunc func() int
type Foo struct{}
// Bar is a method function which is in form of BarFunc.
func (f *Foo) Bar() int {
return 0
}
func (f *Foo) Bind(v interface{}) BarFunc {
if fn, ok := v.(func(*Foo) int); ok {
return func() int {
return fn(f)
}
}
return nil
}
var (
f = &Foo{}
mt, _ = reflect.TypeOf(f).MethodByName("Bar")
mv = reflect.ValueOf(f).MethodByName("Bar")
)
func Benchmark_CallBar1(b *testing.B) {
fn, _ := mv.Interface().(func() int)
for i := 0; i < b.N; i++ {
fn()
}
}
func Benchmark_CallBar2(b *testing.B) {
// This way is 50x faster than Benchmark_CallBar1
fn := f.Bind(mt.Func.Interface())
for i := 0; i < b.N; i++ {
fn()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment