Created
April 10, 2023 13:57
-
-
Save lynxluna/e56d8c9feb25cfd58f6c46ea39b814a1 to your computer and use it in GitHub Desktop.
Animal Testing
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
package animal | |
const ( | |
AnimalDog = iota | |
AnimalCat | |
AnimalBear | |
) | |
type Animal interface { | |
Speak() string | |
} | |
type Dog struct{} | |
func (d Dog) Speak() string { | |
return "Woof!" | |
} | |
type Cat struct{} | |
func (c Cat) Speak() string { | |
return "Meow!" | |
} | |
type Bear struct{} | |
//go:noinline | |
func (b Bear) Speak() string { | |
return "Roar!" | |
} | |
func getAnimal(kind int) Animal { | |
switch kind { | |
case AnimalDog: | |
return Dog{} | |
case AnimalCat: | |
return Cat{} | |
case AnimalBear: | |
return Bear{} | |
default: | |
//everybody loves dogs | |
return Dog{} | |
} | |
} | |
func speakDynamic(animal Animal) string { | |
return animal.Speak() | |
} | |
func speakStaticDog(dog Dog) string { | |
return dog.Speak() | |
} | |
func speakStaticCat(cat Cat) string { | |
return cat.Speak() | |
} | |
func speakStaticBear(bear Bear) string { | |
return bear.Speak() | |
} | |
func speakTypeAssert(animal Animal) string { | |
switch v := animal.(type) { | |
case Dog: | |
var dog Dog = v | |
return dog.Speak() | |
case Cat: | |
var cat Cat = v | |
return cat.Speak() | |
default: | |
return "" | |
} | |
} |
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
package animal | |
import "testing" | |
func BenchmarkDynamicDispatch(b *testing.B) { | |
dog := Dog{} | |
cat := Cat{} | |
for i := 0; i < b.N; i++ { | |
_ = speakDynamic(dog) | |
_ = speakDynamic(cat) | |
} | |
} | |
func BenchmarkStaticDispatch(b *testing.B) { | |
dog := Dog{} | |
cat := Cat{} | |
for i := 0; i < b.N; i++ { | |
_ = speakStaticDog(dog) | |
_ = speakStaticCat(cat) | |
} | |
} | |
func BenchmarkTypeassert(b *testing.B) { | |
dog := Dog{} | |
cat := Cat{} | |
for i := 0; i < b.N; i++ { | |
_ = speakTypeAssert(dog) | |
_ = speakTypeAssert(cat) | |
} | |
} | |
func BenchmarkReturnInterface(b *testing.B) { | |
dog := getAnimal(AnimalDog) | |
cat := getAnimal(AnimalCat) | |
for i := 0; i < b.N; i++ { | |
_ = speakDynamic(dog) | |
_ = speakDynamic(cat) | |
} | |
} | |
func BenchmarkInline(b *testing.B) { | |
dog := Dog{} | |
for i := 0; i < b.N; i++ { | |
_ = dog.Speak() | |
} | |
} | |
func BenchmarkNoInline(b *testing.B) { | |
bear := Bear{} | |
for i := 0; i < b.N; i++ { | |
_ = bear.Speak() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment