golang 几种常见的字符串连接性能比较
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
package main
import (
"bytes"
"fmt"
"strings"
"time"
)
var way map[int]string
func benchmarkStringFunction(n int, index int) (d time.Duration) {
v := "ni shuo wo shi bu shi tai wu liao le a?"
var s string
var buf bytes.Buffer
t0 := time.Now()
for i := 0; i < n; i++ {
switch index {
case 0: // fmt.Sprintf
s = fmt.Sprintf("%s[%s]", s, v)
case 1: // string +
s = s + "[" + v + "]"
case 2: // strings.Join
s = strings.Join([]string{s, "[", v, "]"}, "")
case 3: // stable bytes.Buffer
buf.WriteString("[")
buf.WriteString(v)
buf.WriteString("]")
}
}
d = time.Since(t0)
if index == 3 {
s = buf.String()
}
fmt.Printf("string len: %d\t", len(s))
fmt.Printf("time of [%s]=\t %v\n", way[index], d)
return d
}
func main() {
way = make(map[int]string, 5)
way[0] = "fmt.Sprintf"
way[1] = "+"
way[2] = "strings.Join"
way[3] = "bytes.Buffer"
k := 4
d := [5]time.Duration{}
for i := 0; i < k; i++ {
d[i] = benchmarkStringFunction(10000, i)
}
}
比较结果:
1
2
3
4
string len: 410000 time of [fmt.Sprintf]= 318.093256ms
string len: 410000 time of [+]= 197.03476ms
string len: 410000 time of [strings.Join]= 439.952002ms
string len: 410000 time of [bytes.Buffer]= 435.764µs
下面这种测试更合乎逻辑,避免io:
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
package main
import(
"bytes"
"fmt"
"strings"
"testing"
)
var (
strs = []string{
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
"ten",
}
)
func TestStringsJoin(b *testing.B) {
for i := 0; i < b.N; i++ {
strings.Join(strs, "")
}
}
func TestStringsPlus(b *testing.B) {
for i := 0; i < b.N; i++ {
var s string
for j := 0; j < len(strs); j++ {
s += strs[j]
}
}
}
func TestBytesBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
var b bytes.Buffer
for j := 0; j < len(strs); j++ {
b.WriteString(strs[j])
}
}
}
func main() {
fmt.Println("strings.Join:")
fmt.Println(testing.Benchmark(TestStringsJoin))
fmt.Println("bytes.Buffer:")
fmt.Println(testing.Benchmark(TestBytesBuffer))
fmt.Println("+:")
fmt.Println(testing.Benchmark(TestStringsPlus))
}
结果:
1
2
3
4
5
6
strings.Join:
10000000 139 ns/op
bytes.Buffer:
10000000 166 ns/op
+:
3000000 429 ns/op
go 1.16 速度有点变化
1
2
3
4
5
6
strings.Join:
9492663 124.3 ns/op
bytes.Buffer:
10006905 116.0 ns/op
+:
2761654 434.5 ns/op
本文网址: https://golangnote.com/topic/148.html 转摘请注明来源