Skip to content

Instantly share code, notes, and snippets.

@fogfish
Last active March 9, 2021 09:53
Show Gist options
  • Save fogfish/c4b7eaf7b4505980d39ff464bfdd6de8 to your computer and use it in GitHub Desktop.
Save fogfish/c4b7eaf7b4505980d39ff464bfdd6de8 to your computer and use it in GitHub Desktop.
/*
go test -bench=. -test.benchmem=true -test.benchtime=10s
goos: darwin
goarch: amd64
BenchmarkDirectCall-12 1000000000 1.31 ns/op 0 B/op 0 allocs/op
BenchmarkInterface-12 1000000000 1.69 ns/op 0 B/op 0 allocs/op
BenchmarkHoF-12 1000000000 1.61 ns/op 0 B/op 0 allocs/op
*/
package hof_test
import (
"testing"
)
type Foo struct {
a int
}
type Handler interface {
Serve(x int)
}
type HoF func(x int)
func (foo *Foo) Serve(x int) {
foo.a = foo.a + x
}
func FooHoF(foo *Foo) HoF {
return func(x int) {
foo.a = foo.a + x
}
}
var result Handler
func BenchmarkDirectCall(b *testing.B) {
f := &Foo{}
for n := 0; n < b.N; n++ {
f.Serve(n)
}
result = f
}
func BenchmarkInterface(b *testing.B) {
var f Handler
f = &Foo{}
for n := 0; n < b.N; n++ {
f.Serve(n)
}
result = f
}
func BenchmarkHoF(b *testing.B) {
f := &Foo{}
hof := FooHoF(f)
for n := 0; n < b.N; n++ {
hof(n)
}
result = f
}
@fogfish
Copy link
Author

fogfish commented Mar 9, 2021

Yeah, thanks for notice this! Just updated.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment