-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathappend_test.go
76 lines (65 loc) · 1.66 KB
/
append_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
package main
import (
"fmt"
"testing"
)
var Append []int
type appendBench func(first []int, second []int) []int
func BenchmarkAppend(b *testing.B) {
for _, sizeFirst := range sizes {
for _, sizeSecond := range sizes {
b.Run(
fmt.Sprintf("append_expand(%d)(%d)", sizeFirst, sizeSecond),
benchmarkAppend(sizeFirst, sizeSecond, appendExpand),
)
b.Run(
fmt.Sprintf("append_for(%d)(%d)", sizeFirst, sizeSecond),
benchmarkAppend(sizeFirst, sizeSecond, appendFor),
)
b.Run(
fmt.Sprintf("append_for_prealloc(%d)(%d)", sizeFirst, sizeSecond),
benchmarkAppend(sizeFirst, sizeSecond, appendForPrealloc),
)
b.Run(
fmt.Sprintf("append_for_index(%d)(%d)", sizeFirst, sizeSecond),
benchmarkAppend(sizeFirst, sizeSecond, appendForIdx),
)
}
}
}
func benchmarkAppend(sizeFirst, sizeSecond int, runF appendBench) func(*testing.B) {
first := testingSlice(sizeFirst)
second := testingSlice(sizeSecond)
return func(b *testing.B) {
var f []int
for n := 0; n < b.N; n++ {
f = runF(first, second)
}
Append = f
}
}
func appendExpand(first, second []int) []int {
return append(first, second...)
}
func appendFor(first, second []int) []int {
for _, secondVal := range second {
first = append(first, secondVal)
}
return first
}
func appendForPrealloc(first, second []int) []int {
var out = make([]int, 0, len(first)+len(second))
copy(out, first)
for _, secondVal := range second {
out = append(out, secondVal)
}
return out
}
func appendForIdx(first, second []int) []int {
var out = make([]int, len(first)+len(second))
copy(out, first)
for i, secondVal := range second {
out[(len(first))+i] = secondVal
}
return out
}