Golang 字符串拼接效率

字符串拼接效率对比

  • 下面代码,分别比较了 fmt.Sprintf,string +,strings.Join,bytes.Buffer,方法是循环若干次比较总时间。
  • 性能由高到低依次是(bytes.Buffer) > (string +) > (fmt.Sprintf) > strings.Join

代码

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
package main

import (
"bytes"
"fmt"
"strings"
"time"
)

func benchmarkStringFunction(n int, index int) (d time.Duration) {
v := "abcd efg hijk lmn"
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: // temporary bytes.Buffer
b := bytes.Buffer{}
b.WriteString("[")
b.WriteString(v)
b.WriteString("]")
s = b.String()
case 4: // stable bytes.Buffer
buf.WriteString("[")
buf.WriteString(v)
buf.WriteString("]")
}

if i == n-1 {
if index == 4 { // for stable bytes.Buffer
s = buf.String()
}
fmt.Println(len(s)) // consume s to avoid compiler optimization
}
}
t1 := time.Now()
d = t1.Sub(t0)
fmt.Printf("time of way(%d)=%v\n", index, d)
return d
}

func main() {
k := 5
d := [5]time.Duration{}
for i := 0; i < k; i++ {
d[i] = benchmarkStringFunction(10000, i)
}

for i := 0; i < k-1; i++ {
fmt.Printf("way %d is %6.1f times of way %d\n", i, float32(d[i])/float32(d[k-1]), k-1)
}
}

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
190000
time of way(0)=159.079378ms
190000
time of way(1)=59.071507ms
190000
time of way(2)=77.812168ms
19
time of way(3)=576.325µs
190000
time of way(4)=263.649µs
way 0 is 603.4 times of way 4
way 1 is 224.1 times of way 4
way 2 is 295.1 times of way 4
way 3 is 2.2 times of way 4