Skip to content

Instantly share code, notes, and snippets.

@rrrix
Created March 3, 2023 00:41
Show Gist options
  • Save rrrix/8939a049a069615b83c9bf0fac5ca402 to your computer and use it in GitHub Desktop.
Save rrrix/8939a049a069615b83c9bf0fac5ca402 to your computer and use it in GitHub Desktop.
goos: darwin
goarch: arm64
pkg: github.com/rrrix/go-play/reflect-type-bench
BenchmarkStringType-10       27413637        42.87 ns/op      16 B/op       1 allocs/op
BenchmarkReflectTypeOf-10    205474878        5.824 ns/op      0 B/op       0 allocs/op
BenchmarkSwitchType-10       1000000000       0.8087 ns/op     0 B/op       0 allocs/op✨✨
PASS
ok  github.com/rrrix/go-play/reflect-type-bench4.102s
package typeof
import (
"fmt"
"reflect"
"testing"
)
type Thing struct {
}
func StringFormatType(v interface{}) string {
return fmt.Sprintf("%T", v)
}
func ReflectionTypeToString(v interface{}) string {
return reflect.TypeOf(v).String()
}
func SwitchReflectType(v interface{}) string {
switch v.(type) {
case int:
return "int"
case string:
return "string"
case bool:
return "bool"
case Thing:
return "thing"
default:
return "unknown"
}
}
func BenchmarkStringType(b *testing.B) {
var v Thing
for i := 0; i < b.N; i++ {
StringFormatType(v)
}
}
func BenchmarkReflectTypeOf(b *testing.B) {
var v Thing
for i := 0; i < b.N; i++ {
ReflectionTypeToString(v)
}
}
func BenchmarkSwitchType(b *testing.B) {
var v Thing
for i := 0; i < b.N; i++ {
SwitchReflectType(v)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment