-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathneedle_haystack_test.go
78 lines (67 loc) · 1.73 KB
/
needle_haystack_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
package main
import (
"fmt"
"math/rand"
"testing"
)
var Found bool
type needleInHaystackBench func(checks int, needle int, haystack []int) bool
func BenchmarkNeedleInAHaystack(b *testing.B) {
for _, size := range sizes {
for _, nchecks := range needles {
b.Run(
fmt.Sprintf("slice(%d) needles(%d)", size, nchecks),
benchmarkNeedleInAHaystack(size, nchecks, benchNeedleInAHaystackSlice),
)
b.Run(
fmt.Sprintf("map(%d) needles(%d)", size, nchecks),
benchmarkNeedleInAHaystack(size, nchecks, benchNeedleInAHaystackMap))
}
}
}
func benchmarkNeedleInAHaystack(size int, checks int, runF needleInHaystackBench) func(*testing.B) {
haystack := testingSlice(size)
return func(b *testing.B) {
var f bool
for n := 0; n < b.N; n++ {
needle := rand.Intn(size)
f = runF(checks, needle, haystack)
}
Found = f
}
}
func benchNeedleInAHaystackSlice(checks int, needle int, haystack []int) bool {
var f bool
for i := 0; i < checks; i++ {
f = needleInAHaystackSlice(needle, haystack)
}
return f
}
func needleInAHaystackSlice(needle int, haystack []int) bool {
// This is identical to `slices.Contains` implementation.
for i := range haystack {
if needle == haystack[i] {
return true
}
}
return false
}
func benchNeedleInAHaystackMap(checks int, needle int, haystack []int) bool {
var f bool
mapHaystack := haystackToMap(haystack)
for i := 0; i < checks; i++ {
f = needleInAHaystackMap(needle, mapHaystack)
}
return f
}
func haystackToMap(haystack []int) map[int]struct{} {
var out = make(map[int]struct{}, len(haystack))
for _, v := range haystack {
out[v] = struct{}{}
}
return out
}
func needleInAHaystackMap(needle int, haystack map[int]struct{}) bool {
_, ok := haystack[needle]
return ok
}