Skip to content

Instantly share code, notes, and snippets.

@KScaesar
Created February 12, 2020 06:11
Show Gist options
  • Select an option

  • Save KScaesar/8b4c116188012e06ec939c401f14571d to your computer and use it in GitHub Desktop.

Select an option

Save KScaesar/8b4c116188012e06ec939c401f14571d to your computer and use it in GitHub Desktop.
測試 go 介面的動態執行
// 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