测试代码
1package main
2
3import (
4 "encoding/json"
5 "reflect"
6 "testing"
7)
8
9type A struct {
10 A string `json:"a"`
11 B string `json:"b"`
12 C int `json:"c"`
13 D int `json:"d"`
14 E []string `json:"e"`
15 F []int `json:"f"`
16}
17
18var a = &A{
19 "string",
20 "test",
21 15,
22 1024,
23 []string{"vvv", "ssss", "44444"},
24 []int{100, 4012},
25}
26
27func Struct2Map(value interface{}) map[string]interface{} {
28 v := reflect.ValueOf(value)
29 for v.Kind() == reflect.Ptr {
30 v = v.Elem()
31 }
32 t := v.Type()
33
34 res := make(map[string]interface{})
35 for i := 0; i < t.NumField(); i++ {
36 if tag := t.Field(i).Tag.Get("json"); tag != "" && tag != "-" {
37 res[tag] = v.Field(i).Interface()
38 }
39 }
40 return res
41}
42
43func Struct2MapByJson(value interface{}) map[string]interface{} {
44 bs, err := json.Marshal(value)
45 if err != nil {
46
47 }
48
49 res := make(map[string]interface{})
50 if err := json.Unmarshal(bs, &res); err != nil {
51
52 }
53 return res
54}
55
56func Benchmark_Json2Map(b *testing.B) {
57 for i := 0; i < b.N; i++ {
58 Struct2MapByJson(a)
59 }
60}
61
62func Benchmark_Reflect2Map(b *testing.B) {
63 for i := 0; i < b.N; i++ {
64 Struct2Map(a)
65 }
66}
测试结果
1└──╼ go test -test.bench=".*" .
2goos: darwin
3goarch: amd64
4pkg: maple-test1
5Benchmark_Json2Map-8 241076 4672 ns/op
6Benchmark_Reflect2Map-8 1000000 1005 ns/op
7PASS
8ok maple-test1 2.971s