Benchmark 测试字符串拼接的性能

func BenchmarkStringf(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()
}

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)
		}
	}
	
	b.StopTimer()
}

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()
}

测试数据如下

使用fmt.Sprintf

image

使用字符串相加str = str + strconv.Itoa(j)

使用strings.Builder

命令行运行所有benchmark

➜  ch11 go test -bench='.*'
6666666
goos: linux
goarch: amd64
pkg: awesomeProject/ch11
cpu: AMD Ryzen 5 5600G with Radeon Graphics         
BenchmarkAdd-12                 1000000000               0.2320 ns/op
BenchmarkStringf-12                   49          22959820 ns/op
BenchmarkStringAdd-12                 61          22481787 ns/op
BenchmarkStringBuilder-12           5703            211218 ns/op
PASS
ok      awesomeProject/ch11     4.026s

总结

使用strings.Builder速度最快

posted @ 2023-10-25 23:29  Postkarte  阅读(20)  评论(0)    收藏  举报