Go 语言的 bytes 库有两个有用的字节比较函数 : Compare、Equal
bytes.Compare
Compare 是比较两个 [][]byte
的大小,返回值
0
: a==b-1
: a < b+1
: a > b
bytes.Equal
Equal 直接判断两者是否相等,任务很简单,肯定比 Compare 快
性能比较
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
var bs1 = [][]byte{
[]byte("12a7.0.0.1:109e2"),
[]byte("127.ss.0.aw:1092"),
[]byte("12a.r.0.1:1092cd"),
[]byte("127.0.0.1:1092"),
[]byte("127.s.0.aw:1092"),
[]byte("12a.r.0.1:1092c"),
[]byte("127.0.0.1:1092"),
[]byte("127.s.0.aw:1092"),
[]byte("12a.r.0.1:1092c"),
}
var bs2 = [][]byte{
[]byte("12a7.0.0.1:109e2"),
[]byte("127.ss.0.aw:1092"),
[]byte("12a.r.0.1:1092cd"),
[]byte("127.0.0.1:1092"),
[]byte("127.s.0.aw:1092"),
[]byte("12a.r.0.1:1092c"),
[]byte("12a7.0.0.1:109e2"),
[]byte("127.ss.0.aw:1092"),
[]byte("12a.r.0.1:1092cd"),
}
func Benchmark_bytes_compare(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
for j, s := range bs1 {
if bytes.Compare(s, bs2[j]) != 0 {
// do nothing
}
}
}
}
func Benchmark_bytes_equal(b *testing.B) {
b.ResetTimer()
defer b.StopTimer()
for i := 0; i < b.N; i++ {
for j, s := range bs1 {
if !bytes.Equal(s, bs2[j]) {
// do nothing
}
}
}
}
运行测试
1
go test -v compare_test.go -bench "Benchmark" -benchmem
结果:
1
2
3
4
5
6
7
goos: darwin
goarch: amd64
cpu: Intel(R) Core(TM) i7-4870HQ CPU @ 2.50GHz
Benchmark_bytes_compare
Benchmark_bytes_compare-8 27013251 43.00 ns/op 0 B/op 0 allocs/op
Benchmark_bytes_equal
Benchmark_bytes_equal-8 36742129 29.03 ns/op 0 B/op 0 allocs/op
结果不出所料,快很多,能用 equal 的地方就用它吧。
本文网址: https://golangnote.com/topic/298.html 转摘请注明来源