-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathif_switch_test.go
89 lines (78 loc) · 1.16 KB
/
if_switch_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
package main
import (
"fmt"
"testing"
)
var (
IfSwitch bool
)
type ifSwitchBench func(int) bool
func BenchmarkIfSwitch(b *testing.B) {
b.Run(
fmt.Sprintf("if(1)"),
benchmarkIfSwitch(benchIf1),
)
b.Run(
fmt.Sprintf("switch(1)"),
benchmarkIfSwitch(benchSwitch1),
)
b.Run(
fmt.Sprintf("if(5)"),
benchmarkIfSwitch(benchIf5),
)
b.Run(
fmt.Sprintf("switch(5)"),
benchmarkIfSwitch(benchSwitch5),
)
}
func benchmarkIfSwitch(runF ifSwitchBench) func(*testing.B) {
var input = 5
return func(b *testing.B) {
var f bool
for n := 0; n < b.N; n++ {
f = runF(input)
}
IfSwitch = f
}
}
func benchIf1(in int) bool {
return in == 5
}
func benchSwitch1(in int) bool {
switch in {
case 5:
return true
default:
return false
}
}
func benchIf5(in int) bool {
if in == 1 {
return false
} else if in == 2 {
return false
} else if in == 3 {
return false
} else if in == 4 {
return false
} else if in == 5 {
return true
}
return false
}
func benchSwitch5(in int) bool {
switch in {
case 1:
return false
case 2:
return false
case 3:
return false
case 4:
return false
case 5:
return true
default:
return false
}
}