-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathunordered_test.go
61 lines (47 loc) · 1.07 KB
/
unordered_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
package benchmarks
import (
"fmt"
"math/rand"
"strconv"
"testing"
)
type unordered struct {
id string
value int
}
type unorderedList []unordered
func (ul unorderedList) get(k string) (int, bool) {
for i := range ul {
uo := &ul[i]
if uo.id == k {
return uo.value, true
}
}
return 0, false
}
func (ul unorderedList) add(id string, value int) unorderedList {
return append(ul, unordered{id: id, value: value})
}
func BenchmarkUnorderedList(b *testing.B) {
for _, numToAdd := range []int{1, 10, 25, 100, 500, 1000} {
b.Run(fmt.Sprintf("add_%d", numToAdd), func(b *testing.B) {
l := make(unorderedList, 0, numToAdd)
toadd := make([]string, numToAdd)
for i := range toadd {
toadd[i] = strconv.Itoa(int(rand.Int63()))
}
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i += numToAdd {
benchmarkCheckAndAddEntries(b, numToAdd, l, toadd)
}
})
}
}
func benchmarkCheckAndAddEntries(b *testing.B, numToAdd int, l unorderedList, toadd []string) {
for i, s := range toadd {
if _, ok := l.get(s); !ok {
l = l.add(s, i)
}
}
}