package main import ( "encoding/json" "reflect" "testing" ) type A struct { A string `json:"a"` B string `json:"b"` C int `json:"c"` D int `json:"d"` E []string `json:"e"` F []int `json:"f"` } var a = &A{ "string", "test", 15, 1024, []string{"vvv", "ssss", "44444"}, []int{100, 4012}, } func Struct2Map(value interface{}) map[string]interface{} { v := reflect.ValueOf(value) for v.Kind() == reflect.Ptr { v = v.Elem() } t := v.Type() res := make(map[string]interface{}) for i := 0; i < t.NumField(); i++ { if tag := t.Field(i).Tag.Get("json"); tag != "" && tag != "-" { res[tag] = v.Field(i).Interface() } } return res } func Struct2MapByJson(value interface{}) map[string]interface{} { bs, err := json.Marshal(value) if err != nil { } res := make(map[string]interface{}) if err := json.Unmarshal(bs, &res); err != nil { } return res } func Benchmark_Json2Map(b *testing.B) { for i := 0; i < b.N; i++ { Struct2MapByJson(a) } } func Benchmark_Reflect2Map(b *testing.B) { for i := 0; i < b.N; i++ { Struct2Map(a) } }
└──╼ go test -test.bench=".*" . goos: darwin goarch: amd64 pkg: maple-test1 Benchmark_Json2Map-8 241076 4672 ns/op Benchmark_Reflect2Map-8 1000000 1005 ns/op PASS ok maple-test1 2.971s