对一个字符串做分割操作,可以用 Split
或 Index
来实现,这里对这两者的性能做一个简单比较。
应用场景,对一些特定字符串: ip:port
,取 字符 :
之前的内容
Split
1
2
3
4
5
6
7
8
9
func Benchmark_split(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
for _, s := range ss {
_ = strings.Split(s, ":")[0]
}
}
}
Index
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func Benchmark_index(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
for _, s := range ss {
index := strings.Index(s, ":")
if index == -1 {
_ = s
} else {
_ = s[:index]
}
}
}
}
LastIndex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
func Benchmark_index2(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
for _, s := range ss {
index := strings.LastIndex(s, ":")
if index == -1 {
_ = s
} else {
_ = s[:index]
}
}
}
}
测试
1
go test -v split_test.go -bench "Benchmark" -benchmem
测试的字符串
1
2
3
4
5
var ss = []string{
"127.0.0.1:1092",
"192.168.1.1",
":8080",
}
测试结果
1
2
3
4
5
6
7
8
9
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
Benchmark_split
Benchmark_split-8 5861836 201.1 ns/op 80 B/op 3 allocs/op
Benchmark_index
Benchmark_index-8 66389178 18.14 ns/op 0 B/op 0 allocs/op
Benchmark_index2
Benchmark_index2-8 51777555 22.92 ns/op 0 B/op 0 allocs/op
本文网址: https://golangnote.com/topic/296.html 转摘请注明来源