本文摘自网络,作者,侵删。
基准测试代码
const numbers = 10000
//fmt.Sprintf
func BenchmarkStringSprintf(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var str string
for j := 0; j < numbers; j++ {
str = fmt.Sprintf("%s%d", str, j)
}
}
b.StopTimer()
}
// add
func BenchmarkStringAdd(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var str string
for j := 0; j < numbers; j++ {
str = str + strconv.Itoa(j)
}
}
}
// add
func BenchmarkStringAdd2(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var str string
for j := 0; j < numbers; j++ {
str = str + fmt.Sprintf("%d", j)
}
}
b.StopTimer()
}
//bytes.Buffer
func BenchmarkBytesBuffer(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var buffer bytes.Buffer
for j := 0; j < numbers; j++ {
buffer.WriteString(strconv.Itoa(j))
}
_ = buffer.String()
}
b.StopTimer()
}
//strings.Builder
func BenchmarkStringBuilder(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
var builder strings.Builder
for j := 0; j < numbers; j++ {
builder.WriteString(strconv.Itoa(j))
}
_ = builder.String()
}
b.StopTimer()
}
//strings.Join
func BenchmarkStringJoin(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
strs := make([]string, 0)
for j := 0; j < numbers; j++ {
strs = append(strs, strconv.Itoa(j))
}
strings.Join(strs, "")
}
}
基准测试结果
PS D:\Users\lf\Desktop\coding\golang-study\expirement\strcat> go test -bench=".*"
goos: Windows/">windows
goarch: amd64
BenchmarkStringSprintf-8 16 68860744 ns/op
BenchmarkStringAdd-8 18 63270089 ns/op
BenchmarkStringAdd2-8 19 61748021 ns/op
BenchmarkBytesBuffer-8 2068 582808 ns/op
BenchmarkStringBuilder-8 2324 545157 ns/op
BenchmarkStringJoin-8 991 1075484 ns/op
PASS
ok _/D_/Users/lf/Desktop/coding/golang-study/expirement/strcat 9.836s
这次比较的结果来看 strings.Builder > bytes.Buffer > strings.Join > string add > fmt.Sprintf
分析
fmt.Sprintf
本文来自:简书
感谢作者:IAM_97ed
查看原文:golang几种字符拼接性能分析
相关阅读 >>
Go-carbon 1.2.4 版本发布,新增系列时间比较方法
leetcode153 寻找旋转排序数组中的最小值 Golang
更多相关阅读请进入《Go》频道 >>

Go语言101
一个与时俱进的Go编程知识库。