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
Created
March 3, 2023 00:41
-
-
Save rrrix/8939a049a069615b83c9bf0fac5ca402 to your computer and use it in GitHub Desktop.
Benchmarks for getting object type in go. http://stackoverflow.com/a/27160765/2078664 based on https://gist.github.com/mrap/7f08c9549289b6aea2923c27888e7e3e
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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