golang笔记之struct转map性能比较


Table of Contents

测试代码

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
作者: honmaple
链接: https://honmaple.me/articles/2020/09/golang笔记之struct转map性能比较.html
版权: CC BY-NC-SA 4.0 知识共享署名-非商业性使用-相同方式共享4.0国际许可协议
wechat
alipay

加载评论