Skip to content

Instantly share code, notes, and snippets.

@mwf
Last active February 11, 2019 15:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mwf/af9cfbb3a1b53616630b8cff7c6cde5d to your computer and use it in GitHub Desktop.
Save mwf/af9cfbb3a1b53616630b8cff7c6cde5d to your computer and use it in GitHub Desktop.
Go Interface conversion benchmarks
package example
import (
"testing"
)
type foo struct {
name string
}
const (
stringConst = "omg"
)
var (
pointer = &foo{"foo"}
)
func nop(_ interface{}) {}
func BenchmarkInterfaceConversion(b *testing.B) {
b.Run("pointer", func(b *testing.B) {
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(pointer)
}
nop(f)
})
b.Run("not a pointer", func(b *testing.B) {
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(foo{"foo"})
}
nop(f)
})
b.Run("const string", func(b *testing.B) {
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(stringConst)
}
nop(f)
})
b.Run("string", func(b *testing.B) {
var k string = "foo"
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(k)
}
nop(f)
})
b.Run("int8", func(b *testing.B) {
var k int8 = 100
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(k)
}
nop(f)
})
b.Run("int16", func(b *testing.B) {
var k int16 = 1024
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(k)
}
nop(f)
})
b.Run("float32", func(b *testing.B) {
var k float32 = 1
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(k)
}
nop(f)
})
b.Run("slice", func(b *testing.B) {
k := make([]int, 10000)
for i := 0; i < len(k); i++ {
k[i] = i
}
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(k)
}
nop(f)
})
b.Run("map", func(b *testing.B) {
k := map[int]string{1: "fooo"}
var f interface{}
for i := 0; i < b.N; i++ {
f = interface{}(k)
}
nop(f)
})
}
go test -benchmem -bench .
goos: darwin
goarch: amd64
BenchmarkInterfaceConversion/pointer-4 2000000000 0.53 ns/op 0 B/op 0 allocs/op
BenchmarkInterfaceConversion/not_a_pointer-4 50000000 29.5 ns/op 16 B/op 1 allocs/op
BenchmarkInterfaceConversion/const_string-4 2000000000 0.27 ns/op 0 B/op 0 allocs/op
BenchmarkInterfaceConversion/string-4 50000000 24.0 ns/op 16 B/op 1 allocs/op
BenchmarkInterfaceConversion/int8-4 2000000000 0.26 ns/op 0 B/op 0 allocs/op
BenchmarkInterfaceConversion/int16-4 100000000 11.0 ns/op 2 B/op 1 allocs/op
BenchmarkInterfaceConversion/float32-4 100000000 11.0 ns/op 4 B/op 1 allocs/op
BenchmarkInterfaceConversion/slice-4 50000000 29.6 ns/op 32 B/op 1 allocs/op
BenchmarkInterfaceConversion/map-4 2000000000 0.26 ns/op 0 B/op 0 allocs/op
PASS
ok _/var/folders/_b/d1934m9s587_8t_6ngv3hnc00000gp/T/tmp.kFulmEtK 9.275s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment