Last active
March 9, 2021 09:53
-
-
Save fogfish/c4b7eaf7b4505980d39ff464bfdd6de8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yeah, thanks for notice this! Just updated.