Closed EinKrebs closed 2 years ago
I initially started with fmt.Sprintf
, but ended up with strings.Builder
precisely because of what @chhetripradeep noted.
@chhetripradeep @bobrik thank you for advice, gonna revert this.
@chhetripradeep @bobrik @pavolloffay I got interesting results testing also strings concatenation.
func BenchmarkStringsBuilder(b *testing.B) {
buf := &strings.Builder{}
tags := generateRandomKeyValues(b.N)
b.StartTimer()
for i := 0; i < b.N; i++ {
buf.Reset()
buf.WriteString(tags[i].Key)
buf.WriteByte('=')
buf.WriteString(tags[i].AsString())
_ = buf.String()
}
}
func BenchmarkFmtSprintf(b *testing.B) {
tags := generateRandomKeyValues(b.N)
b.StartTimer()
for i := 0; i < b.N; i++ {
_ = fmt.Sprintf("%s=%s", tags[i].Key, tags[i].AsString())
}
}
func BenchmarkPlus(b *testing.B) {
tags := generateRandomKeyValues(b.N)
b.StartTimer()
for i := 0; i < b.N; i++ {
_ = tags[i].Key + "=" + tags[i].AsString()
}
}
There are the results
BenchmarkStringsBuilder
BenchmarkStringsBuilder-12 3488994 328.0 ns/op
BenchmarkFmtSprintf
BenchmarkFmtSprintf-12 2865664 407.5 ns/op
BenchmarkPlus
BenchmarkPlus-12 3997849 298.3 ns/op
I guess I'll use concatenation after all.
concatenation seems better to me for this use-case.
@EinKrebs I am not sure what was the motivation behind this PR. I thought that
strings.Builder
is faster thanfmt.Sprintf