通过 https://www.cnblogs.com/vinsent/p/11281777.html页面,可以看到golang用来完成字符串拼接的几种常用方式。这里测试下几个方式性能上的区别。
1:运算符+方式
2: fmt.Sprint
3: strings.Join
4: strings.Builder bytes.Buffer 这两个方式差不多
这里检测下以上4中类型的效率。测试代码如下
import (
"fmt"
"strings"
"testing"
)
var msg = "https://www.cnblogs.com/vinsent/p/11281777.html"
func BenchmarkFmt(b *testing.B) {
for i := 0; i <= b.N; i++ {
fmt.Sprintf("%s%s%s%s%s",
msg,
msg,
msg,
msg,
msg,
)
}
}
func BenchmarkJoin(b *testing.B) {
for i := 0; i <= b.N; i++ {
strings.Join([]string{msg,msg,msg,msg,msg}, "")
}
}
func BenchmarkBuild(b *testing.B) {
var bd strings.Builder
bd.Grow(len(msg) * 5)
b.ResetTimer()
for i := 0; i <= b.N; i++ {
bd.WriteString(msg)
bd.WriteString(msg)
bd.WriteString(msg)
bd.WriteString(msg)
bd.WriteString(msg)
bd.Reset()
}
}
func BenchmarkAdd(b *testing.B) {
var s string
b.ResetTimer()
for i := 0; i <= b.N; i++ {
s += msg
s += msg
s += msg
s += msg
s += msg
s = ""
}
}
测试环境 & 测试命令
[root@localhost tmp]# go test -bench=. -benchmem
goos: linux
goarch: amd64
pkg: /tmp
BenchmarkFmt-2 1031640 1314 ns/op 320 B/op 6 allocs/op
BenchmarkJoin-2 3192985 372 ns/op 240 B/op 1 allocs/op
BenchmarkBuild-2 1548115 775 ns/op 720 B/op 4 allocs/op
BenchmarkAdd-2 1000000 1004 ns/op 672 B/op 4 allocs/op
PASS ok /tmp 6.808s
这里看得出Jonin的方式最好,strings.Builder 其次。
不过测试和 msg的长度有关,
当msg的长度增加10倍之后 测试结果如下
[root@localhost tmp]# go test -bench=. -benchmem
goos: linux
goarch: amd64
pkg: /tmp
BenchmarkFmt-2 495908 2412 ns/op 2768 B/op 6 allocs/op
BenchmarkJoin-2 952504 1088 ns/op 2688 B/op 1 allocs/op
BenchmarkBuild-2 436336 2301 ns/op 6240 B/op 4 allocs/op
BenchmarkAdd-2 377988 2825 ns/op 7296 B/op 4 allocs/op
PASS
ok /tmp 5.317s
[root@localhost tmp]#
msg长度增加10倍, Join的性能降低的最多,其次是strings.Builder,
当msg长度增加30倍之后 测试结果如下
pkg: /tmp
BenchmarkFmt-2 286434 4218 ns/op 8272 B/op 6 allocs/op
BenchmarkJoin-2 451930 2643 ns/op 8192 B/op 1 allocs/op
BenchmarkBuild-2 159805 6579 ns/op 23808 B/op 5 allocs/op
BenchmarkAdd-2 186258 5998 ns/op 22272 B/op 4 allocs/op
PASS ok /tmp 6.776s
这下 strings.Builder的性能反而降到最低了。
综合一下,Join的性能最好。以后尽量多用这个来拼接吧。
有疑问加站长微信联系(非本文作者)
![](https://static.golangjob.cn/static/img/footer.png?imageView2/2/w/280)