Go有多种字符串拼接方式,不同方式的效率不同:
- 使用加号+
- bytes.Buffer
- strings.Builder 效率最佳
- copy()
- strings.Join()
- 测试
go test -bench=. -benchmem
Concatenating_test.go
package main
import (
"bytes"
"strings"
"testing"
)
func BenchmarkConcat(b *testing.B) {
var str string
b.ResetTimer()
for i := 0; i < b.N; i++ {
str += "x"
}
b.StopTimer()
if s := strings.Repeat("x", b.N); str != s {
b.Errorf("Unexpected result: got:%s want:%s", str, s)
}
}
func BenchmarkBuffer(b *testing.B) {
var buf bytes.Buffer
b.ResetTimer()
for i := 0; i < b.N; i++ {
buf.WriteString("x")
}
b.StopTimer()
if s := strings.Repeat("x", b.N); buf.String() != s {
b.Errorf("Unexpected result: got:%s want:%s", buf.String(), s)
}
}
func BenchmarkStringBuilder(b *testing.B) {
var strBuilder strings.Builder
b.ResetTimer()
for i := 0; i < b.N; i++ {
strBuilder.WriteString("x")
}
b.StopTimer()
if s := strings.Repeat("x", b.N); strBuilder.String() != s {
b.Errorf("Unexpected result: got:%s want:%s", strBuilder.String(), s)
}
}
func BenchmarkCopy(b *testing.B) {
bs := make([]byte, b.N)
bl := 0
b.ResetTimer()
for i := 0; i < b.N; i++ {
bl += copy(bs[bl:], "x")
}
b.StopTimer()
if s := strings.Repeat("x", b.N); string(bs) != s {
b.Errorf("Unexpected result: got:%s want:%s", string(bs), s)
}
}
func BenchmarkStringJoin(b *testing.B) {
var strSlice []string
b.ResetTimer()
for i := 0; i < b.N; i++ {
strSlice = append(strSlice, "x")
}
b.StopTimer()
if s, str := strings.Repeat("x", b.N), strings.Join(strSlice, ""); str != s {
b.Errorf("Unexpected result: got:%s want:%s", str, s)
}
}
测试结果
BenchmarkConcat-8 1000000 39347 ns/op 503994 B/op 1 allocs/op
BenchmarkBuffer-8 200000000 8.63 ns/op 2 B/op 0 allocs/op
BenchmarkStringBuilder-8 1000000000 3.29 ns/op 6 B/op 0 allocs/op
BenchmarkCopy-8 300000000 4.30 ns/op 0 B/op 0 allocs/op
BenchmarkStringJoin-8 20000000 86.6 ns/op 80 B/op 0 allocs/op
网友评论