【Golang】 变量深拷贝方案

零、公共代码

 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
package main

import (
	"fmt"
	"unsafe"
)

var p1 = Person{
	Name: "aaa",
	Params: map[string]string{
		"param1": "value1",
		"param2": "value2",
	},
	Next: &Person{
		Name: "bbb",
		Params: map[string]string{
			"param3": "value3",
			"param4": "value4",
		},
	},
}

type Person struct {
	Name   string
	Params map[string]string
	Next   *Person
}

一、反射方案

使用库:github.com/mohae/deepcopy

示例代码:

1
2
3
4
5
6

import "github.com/mohae/deepcopy"

func main() {
    p2 := deepcopy.Copy(p1).(types.Person)
}

性能:

1
BenchmarkDeepCopy-8   	  775651	      1503 ns/op

二、使用json

安装高性能的json库:github.com/json-iterator/go

 1
 2
 3
 4
 5
 6
 7
 8
 9
10

import jsoniter "github.com/json-iterator/go"

var json = jsoniter.ConfigCompatibleWithStandardLibrary
var p1j = json.Marshal(p1)

func main() {
	var p2 types.Person
	err := json.Unmarshal(p1j, &p2)
}

性能:

1
2
# json-iterator 库性能
BenchmarkJsonIterJSON-8   	 1332277	       885.5 ns/op
1
2
# 标准库性能
BenchmarkStdJSON-8   	  541288	      2128 ns/op

三、k8s提供的deepcopy-gen

安装生成工具:

1
go install k8s.io/code-generator/cmd/deepcopy-gen

添加doc.go文件:

1
2
3
4
5
6
// file: doc.go

// 此处是核心注解
// +k8s:deepcopy-gen=package

package main

执行命令生成deepcopy代码:

1
deepcopy-gen --output-file generated.deepcopy.go your_module_name/...

示例代码:

1
2
3
func main() {
	p2 := p1.DeepCopy()
}

性能

1
BenchmarkK8sDepCopy-8   	 4201444	       294.9 ns/op
Licensed under CC BY-NC-SA 4.0