字符串拼接方式性能对比

测试

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

import (
"bytes"
"fmt"
"strings"
"testing"
)

const v string = "ni shuo wo shi bu shi tai wu liao le a?"

func BenchmarkTest1(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s = fmt.Sprintf("%s[%s]", s, v)
}
}

func BenchmarkTest2(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s = strings.Join([]string{s, "[", v, "]"}, "")
}
}

func BenchmarkTest3(b *testing.B) {
buf := bytes.Buffer{}
for i := 0; i < b.N; i++ {
buf.WriteString("[")
buf.WriteString(v)
buf.WriteString("]")
}
}

func BenchmarkTest4(b *testing.B) {
var s string
for i := 0; i < b.N; i++ {
s = s + "[" + v + "]"
}
}

go test -v -test.bench=”.” -benchmem String_concatenation_test.go

1
2
3
4
5
6
7
8
goos: darwin
goarch: amd64
BenchmarkTest1-4 50000 171597 ns/op 2063850 B/op 4 allocs/op
BenchmarkTest2-4 50000 137827 ns/op 1029071 B/op 1 allocs/op
BenchmarkTest3-4 20000000 85.8 ns/op 86 B/op 0 allocs/op
BenchmarkTest4-4 50000 87791 ns/op 1029071 B/op 1 allocs/op
PASS
ok command-line-arguments 22.715s

结论

  • fmt.Sprintf 和 strings.Join 速度相当
  • string + 比上述二者快一倍
  • bytes.Buffer又比上者快约400-500倍

参考资料:

golang 几种常见的字符串连接性能比较