-
Notifications
You must be signed in to change notification settings - Fork 1
/
range_func_test.go
57 lines (49 loc) · 1.11 KB
/
range_func_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
package main
import (
"fmt"
"testing"
)
var Accum int
func BenchmarkRangeFunc(b *testing.B) {
for _, size := range sizes {
for _, iterations := range sizes {
b.Run(
fmt.Sprintf("slice(%d) iterations(%d)", size, iterations),
benchmarkSliceIterate(size, iterations),
)
b.Run(
fmt.Sprintf("iter func(%d) iterations(%d)", size, iterations),
benchmarkRangeFuncIterate(size, iterations))
}
}
}
func benchmarkSliceIterate(size, iterations int) func(*testing.B) {
return func(b *testing.B) {
var acc int
for n := 0; n < b.N; n++ {
for i := 0; i <= iterations; i++ {
// Here we have to allocate the iteration slice
// as that is the main benefit of range over func
// - no upfront allocation.
iterSlice := testingSlice(size)
for _, val := range iterSlice {
acc += val
}
}
}
Accum = acc
}
}
func benchmarkRangeFuncIterate(size, iterations int) func(*testing.B) {
return func(b *testing.B) {
var acc int
for n := 0; n < b.N; n++ {
for i := 0; i <= iterations; i++ {
for val := range testingIter(size) {
acc += val
}
}
}
Accum = acc
}
}