Skip to content

Instantly share code, notes, and snippets.

@mrap
Created April 6, 2017 20:50
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mrap/7f08c9549289b6aea2923c27888e7e3e to your computer and use it in GitHub Desktop.
Save mrap/7f08c9549289b6aea2923c27888e7e3e to your computer and use it in GitHub Desktop.
Benchmarks for getting object type in go. http://stackoverflow.com/a/27160765/2078664

go test -bench=. -benchmem

BenchmarkTypeof-4          	10000000	       153 ns/op	      16 B/op	       1 allocs/op
BenchmarkReflectTypeOf-4   	50000000	        27.4 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/mrap/bench/typeof	3.099s
package typeof_test
import (
"fmt"
"reflect"
"testing"
)
type T struct {
}
func typeof(v interface{}) string {
return fmt.Sprintf("%T", v)
}
func reflectTypeof(v interface{}) string {
return reflect.TypeOf(v).String()
}
func BenchmarkTypeof(b *testing.B) {
var v T
for i := 0; i < b.N; i++ {
typeof(v)
}
}
func BenchmarkReflectTypeOf(b *testing.B) {
var v T
for i := 0; i < b.N; i++ {
reflectTypeof(v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment