• go深度拷贝reflect版


    使用 reflecting 和 gob 两种方式,性能比较结果:

    Deep copy with reflecting is 10x faster than gob and it will save more memory.
    

    reflecting 使用库 https://github.com/mohae/deepcopy 76 过程参见 https://xuri.me/2018/06/17/deep-copy-object-with-reflecting-or-gob-in-go.html 60

    2.通过反射的方式拷贝结构

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    117
    118
    119
    120
    121
    122
    123
    124
    125
    126
    127
    128
    129
    130
    131
    132
    133
    134
    135
    136
    137
    138
    139
    140
    141
    142
    143
    144
    145
    146
    147
    148
    149
    150
    151
    152
    153
    154
    155
    156
    157
    158
    159
    160
    161
    162
    163
    164
    165
    166
    167
    168
    169
    170
    171
    172
    173
    174
    175
    176
    177
    178
    179
    180
    package main
     
    import (
    "fmt"
    "reflect"
    "time"
    )
     
    type (
        Player struct {
            Id     int
            Level  int
            Heroes map[int]*Hero
            Equips []*Equip
        }
     
        Hero struct {
            Id     int
            Level  int
            Skills []*Skill
        }
     
        Equip struct {
            Id    int
            Level int
        }
     
        Skill struct {
            Id    int
            Level int
        }
    )
     
    func NewHero() *Hero {
        return &Hero{
            Id:     1,
            Level:  1,
            Skills: append([]*Skill{NewSkill()}, NewSkill(), NewSkill()),
        }
    }
     
    func NewSkill() *Skill {
        return &Skill{1, 1}
    }
     
    func NewEquip() *Equip {
        return &Equip{1, 1}
    }
     
    func NewPlayer() *Player {
        return &Player{
            Id:     1,
            Level:  1,
            Heroes:   map[int]*Hero{1: NewHero(), 2: NewHero(), 3: NewHero()},
            Equips: append([]*Equip{NewEquip()}, NewEquip(), NewEquip()),
        }
    }
     
    func (self *Hero) Print() {
        fmt.Printf("Id=%d, Level=%d ", self.Id, self.Level)
        for _, v := range self.Skills {
            fmt.Printf("%v ", *v)
        }
    }
     
    func (self *Player) Print() {
        fmt.Printf("Id=%d, Level=%d ", self.Id, self.Level)
        for _, v := range self.Heroes {
            v.Print()
        }
     
        for _, v := range self.Equips {
            fmt.Printf("%+v ", *v)
        }
    }
     
    type Interface interface {
        DeepCopy() interface{}
    }
     
    func Copy(src interface{}) interface{} {
        if src == nil {
            return nil
        }
        original := reflect.ValueOf(src)
        cpy := reflect.New(original.Type()).Elem()
        copyRecursive(original, cpy)
     
        return cpy.Interface()
    }
     
    func copyRecursive(src, dst reflect.Value) {
        if src.CanInterface() {
            if copier, ok := src.Interface().(Interface); ok {
                dst.Set(reflect.ValueOf(copier.DeepCopy()))
                return
            }
        }
     
        switch src.Kind() {
        case reflect.Ptr:
            originalValue := src.Elem()
     
            if !originalValue.IsValid() {
                return
            }
            dst.Set(reflect.New(originalValue.Type()))
            copyRecursive(originalValue, dst.Elem())
     
        case reflect.Interface:
            if src.IsNil() {
                return
            }
            originalValue := src.Elem()
            copyValue := reflect.New(originalValue.Type()).Elem()
            copyRecursive(originalValue, copyValue)
            dst.Set(copyValue)
     
        case reflect.Struct:
            t, ok := src.Interface().(time.Time)
            if ok {
                dst.Set(reflect.ValueOf(t))
                return
            }
            for i := 0; i < src.NumField(); i++ {
                if src.Type().Field(i).PkgPath != "" {
                    continue
                }
                copyRecursive(src.Field(i), dst.Field(i))
            }
     
        case reflect.Slice:
            if src.IsNil() {
                return
            }
            dst.Set(reflect.MakeSlice(src.Type(), src.Len(), src.Cap()))
            for i := 0; i < src.Len(); i++ {
                copyRecursive(src.Index(i), dst.Index(i))
            }
     
        case reflect.Map:
            if src.IsNil() {
                return
            }
            dst.Set(reflect.MakeMap(src.Type()))
            for _, key := range src.MapKeys() {
                originalValue := src.MapIndex(key)
                copyValue := reflect.New(originalValue.Type()).Elem()
                copyRecursive(originalValue, copyValue)
                copyKey := Copy(key.Interface())
                dst.SetMapIndex(reflect.ValueOf(copyKey), copyValue)
            }
     
        default:
            dst.Set(src)
        }
    }
     
    func main() {
        p1 := NewPlayer()
        p2 := Copy(p1).(*Player)
        fmt.Println(reflect.DeepEqual(p1, p2))
    }
     
    // 输出
    true
     
    // benchamark测试
    func BenchmarkReflect(b *testing.B) {
        p1 := NewPlayer()
        for i:=0 ; i<b.N ; i++ {
            Copy(p1)
        }
    }
     
    goos: windows
    goarch: amd64
    pkg: game.lab/go-deepcopy/src/reflect
    200000       10725 ns/op
    PASS
  • 相关阅读:
    MySQL和B树的那些事
    记一次临时抱佛脚的性能压测经历
    zookeeper api
    zookeeper笔记
    Mysql优化系列(1)--Innodb重要参数优化
    搞懂MySQL InnoDB B+树索引
    我以为我对Mysql索引很了解,直到我遇到了阿里的面试官
    HDFS原理概念扫盲
    设计原则
    设计模式 6大则
  • 原文地址:https://www.cnblogs.com/ExMan/p/14292032.html
Copyright © 2020-2023  润新知