Created
February 12, 2020 06:11
-
-
Save KScaesar/8b4c116188012e06ec939c401f14571d to your computer and use it in GitHub Desktop.
測試 go 介面的動態執行
This file contains hidden or 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
| // main.go | |
| package main | |
| type Duck interface { | |
| Quack() | |
| } | |
| type Cat struct { | |
| Name string | |
| } | |
| //go:noinline | |
| func (c Cat) Quack() { | |
| // println(c.Name + " meow") | |
| // _ = c.Name + " meow" | |
| } | |
| func main() { | |
| } | |
| // main_test.go | |
| package main | |
| import ( | |
| "testing" | |
| ) | |
| func BenchmarkDirectCall(b *testing.B) { | |
| c := &Cat{Name: "grooming"} | |
| for n := 0; n < b.N; n++ { | |
| // c := &Cat{Name: "grooming"} | |
| c.Quack() | |
| } | |
| } | |
| func BenchmarkDynamicDispatchByPointer(b *testing.B) { | |
| c := Duck(&Cat{Name: "grooming"}) | |
| for n := 0; n < b.N; n++ { | |
| // c := Duck(&Cat{Name: "grooming"}) | |
| c.Quack() | |
| } | |
| } | |
| func BenchmarkDynamicDispatchByValue(b *testing.B) { | |
| c := Duck(Cat{Name: "grooming"}) | |
| for n := 0; n < b.N; n++ { | |
| // c := Duck(Cat{Name: "grooming"}) | |
| c.Quack() | |
| } | |
| } | |
| // bash | |
| $ go test -gcflags=-N -benchmem -test.count=1 -test.cpu=1 -test.benchtime=1s -bench . | |
| goos: windows | |
| goarch: amd64 | |
| pkg: escape | |
| BenchmarkDirectCall 593879478 1.97 ns/op 0 B/op 0 allocs/op | |
| BenchmarkDynamicDispatchByPointer 326106717 3.65 ns/op 0 B/op 0 allocs/op | |
| BenchmarkDynamicDispatchByValue 339610946 3.50 ns/op 0 B/op 0 allocs/op | |
| PASS | |
| ok escape 4.638s | |
| $ go version | |
| go version go1.13.3 windows/amd64 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment