Code
package main
import (
"testing"
)
func Add[T int](a, b T) T {
return a + b
}
func AddInterface(a, b interface{}) interface{} {
return a.(int) + b.(int)
}
func AddInt(i, j int) int {
return i + j
}
func BenchmarkAddGeneric(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = Add[int](i, i+1)
}
}
func BenchmarkAddInterface(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = AddInterface(i, i+1)
}
}
func BenchmarkAddInt(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = AddInt(i, i+1)
}
}
go version go1.18.9 darwin/arm64
BenchmarkAddGeneric-10 1000000000 0.3187 ns/op
BenchmarkAddInterface-10 1000000000 0.3146 ns/op
BenchmarkAddInt-10 1000000000 0.3162 ns/op
go version go1.19.9 darwin/arm64
BenchmarkAddGeneric-10 1000000000 0.9443 ns/op
BenchmarkAddInterface-10 1000000000 0.3174 ns/op
BenchmarkAddInt-10 1000000000 0.3143 ns/op
go version go1.20.5 darwin/arm64
BenchmarkAddGeneric-10 1000000000 0.3164 ns/op
BenchmarkAddInterface-10 1000000000 0.3152 ns/op
BenchmarkAddInt-10 1000000000 0.3162 ns/op