/
hostport_test.go
91 lines (80 loc) · 1.79 KB
/
hostport_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
90
91
package main
import (
"fmt"
"net"
"strings"
"testing"
)
// var testHostPort = "127.0.0.1:1234"
var testHostPort = "127.127.127.127:1234"
const printHost = false
// getHostStd uses strings.IndexByte to find the location of the colon
// and returns the string up to that point.
func getHostIndexByte(hostPort string) string {
if idx := strings.IndexByte(hostPort, ':'); idx > 0 {
return hostPort[:idx]
}
return hostPort
}
func getHostSplitHostPort(hostPort string) string {
if host, _, err := net.SplitHostPort(hostPort); err == nil {
return host
}
return hostPort
}
// getHostIndexLoop uses a for loop to find the location of the colon and
// returns the string up to that point.
func getHostIndexLoop(hostPort string) string {
for i := 0; i < len(hostPort); i++ {
if hostPort[i] == ':' {
return hostPort[:i]
}
}
return hostPort
}
// getHostRangeLoop uses a for loop to find the location of the colon and
// returns the string up to that point.
func getHostRangeLoop(hostPort string) string {
for i, c := range hostPort {
if c == ':' {
return hostPort[:i]
}
}
return hostPort
}
func BenchmarkGetHostIndexByte(b *testing.B) {
var host string
for i := 0; i < b.N; i++ {
host = getHostIndexByte(testHostPort)
}
if printHost {
fmt.Println(host)
}
}
func BenchmarkGetHostSplitHostPort(b *testing.B) {
var host string
for i := 0; i < b.N; i++ {
host = getHostSplitHostPort(testHostPort)
}
if printHost {
fmt.Println(host)
}
}
func BenchmarkGetHostIndexLoop(b *testing.B) {
var host string
for i := 0; i < b.N; i++ {
host = getHostIndexLoop(testHostPort)
}
if printHost {
fmt.Println(host)
}
}
func BenchmarkGetHostRangeLoop(b *testing.B) {
var host string
for i := 0; i < b.N; i++ {
host = getHostRangeLoop(testHostPort)
}
if printHost {
fmt.Println(host)
}
}