-
Notifications
You must be signed in to change notification settings - Fork 0
/
slice_clone_test.go
102 lines (87 loc) · 1.65 KB
/
slice_clone_test.go
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
package main_test
import (
"testing"
"golang.org/x/exp/slices"
)
// Just for reference as obviously that's what copy() is for.
// also to "warm up" the benchmarks.
func Clone0(src []byte) []byte {
dst := make([]byte, 0, len(src))
for i := range src {
dst = append(dst, src[i])
}
return dst
}
func Clone1(src []byte) []byte {
dst := make([]byte, len(src))
copy(dst, src)
return dst
}
func Clone2(src []byte) []byte {
return append([]byte{}, src...)
}
var Clone3 = slices.Clone[[]byte]
func Clone4(src []byte) []byte {
dst := make([]byte, 0, len(src))
dst = append(dst, src...)
return dst
}
func Clone5(src []byte) []byte {
return append([]byte(nil), src...)
}
// Clearly this is a small slice so only one of many cases...
var byteSlice = []byte("hello world, how are you?")
func BenchmarkClone0(b *testing.B) {
var res []byte
for i := 0; i < b.N; i++ {
res = Clone0(byteSlice)
}
if res[0] == 0 {
b.Log(res)
}
}
func BenchmarkClone1(b *testing.B) {
var res []byte
for i := 0; i < b.N; i++ {
res = Clone1(byteSlice)
}
if res[0] == 0 {
b.Log(res)
}
}
func BenchmarkClone2(b *testing.B) {
var res []byte
for i := 0; i < b.N; i++ {
res = Clone2(byteSlice)
}
if res[0] == 0 {
b.Log(res)
}
}
func BenchmarkClone3(b *testing.B) {
var res []byte
for i := 0; i < b.N; i++ {
res = slices.Clone(byteSlice)
}
if res[0] == 0 {
b.Log(res)
}
}
func BenchmarkClone4(b *testing.B) {
var res []byte
for i := 0; i < b.N; i++ {
res = Clone4(byteSlice)
}
if res[0] == 0 {
b.Log(res)
}
}
func BenchmarkClone5(b *testing.B) {
var res []byte
for i := 0; i < b.N; i++ {
res = Clone5(byteSlice)
}
if res[0] == 0 {
b.Log(res)
}
}