Skip to content

Instantly share code, notes, and snippets.

@runeimp
Created October 9, 2019 23:09
Show Gist options
  • Save runeimp/5bc90e22d4e2d556a9edfc3da1857e7d to your computer and use it in GitHub Desktop.
Save runeimp/5bc90e22d4e2d556a9edfc3da1857e7d to your computer and use it in GitHub Desktop.
Go TypeOf Benchmark

TypeOf

Original code from https://gist.github.com/mrap/7f08c9549289b6aea2923c27888e7e3e

All Three TypeOf Options

$ go test -bench=. -benchmem
goos: darwin
goarch: amd64
BenchmarkFormatTypeOf-8          11032510               105.0 ns/op           16 B/op          1 allocs/op
BenchmarkReflectTypeOf-8         99367936                12.0 ns/op            0 B/op          0 allocs/op
BenchmarkSwitchTypeOf-8         409517779                 2.9 ns/op            0 B/op          0 allocs/op
PASS
ok      _/Users/runeimp/dev/lang/go/runeimp/src/runeimp/typeof  4.009s

Tests performed with this version of Go

$ go version
go version go1.13.1 darwin/amd64
package typeof_test
// Expanded from code found at https://gist.github.com/mrap/7f08c9549289b6aea2923c27888e7e3e
// Expansion was the addition of switchTypeOf and BenchmarkSwitchTypeOf
import (
"fmt"
"reflect"
"testing"
)
type T struct{}
func formatTypeOf(v interface{}) string {
return fmt.Sprintf("%T", v)
}
func reflectTypeOf(v interface{}) string {
return reflect.TypeOf(v).String()
}
func switchTypeOf(v interface{}) string {
switch v.(type) {
case struct{}:
return "struct"
default:
return "unknown"
}
return "unknown"
}
func BenchmarkFormatTypeOf(b *testing.B) {
var v T
for i := 0; i < b.N; i++ {
formatTypeOf(v)
}
}
func BenchmarkReflectTypeOf(b *testing.B) {
var v T
for i := 0; i < b.N; i++ {
reflectTypeOf(v)
}
}
func BenchmarkSwitchTypeOf(b *testing.B) {
var v T
for i := 0; i < b.N; i++ {
switchTypeOf(v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment