String concatenation in golang since 1.10 (bytes.Buffer vs strings.Builder)

Felipe Dutra Tine e Silva
2 min readSep 26, 2018

--

string concatenation is one of the subject we heard about in all languages.

In golang, as others language, you can do such things in many ways.

bytes.Buffer

Before golang 1.10 the most effective way was to use bytes.Buffer.

func CreateKeyBuf(keys ...string) string {
var b bytes.Buffer
for i := 0; i < len(keys); i++ {
b.WriteString(keys[i])
}
return b.String()
}
var Result stringfunc BenchmarkCreateKeyBuf1(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
result = CreateKeyBuf("a")
}
Result = result
}
func BenchmarkCreateKeyBuf2(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
result = CreateKeyBuf("a", "b")
}
Result = result
}
func BenchmarkCreateKeyBuf3(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
result = CreateKeyBuf("a", "b", "c")
}
Result = result
}

if we benchmark it :

go test -run=^$ -bench=. -benchmemgoos: linux
goarch: amd64
pkg: github.com/tkanos/console/escape
BenchmarkCreateKeyBuf1-8 20000000 62.8 ns/op 112 B/op 1 allocs/op
BenchmarkCreateKeyBuf2-8 20000000 95.5 ns/op 114 B/op 2 allocs/op
BenchmarkCreateKeyBuf3-8 10000000 134 ns/op 115 B/op 2 allocs/op

strings.Builder

func CreateKeyString(keys ...string) string {
var b strings.Builder
for i := 0; i < len(keys); i++ {
b.WriteString(keys[i])
}
return b.String()
}
var Result stringfunc BenchmarkCreateKeyString1(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
result = CreateKeyString("a")
}
Result = result
}
func BenchmarkCreateKeyString2(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
result = CreateKeyString("a", "b")
}
Result = result
}
func BenchmarkCreateKeyString3(b *testing.B) {
var result string
for n := 0; n < b.N; n++ {
result = CreateKeyString("a", "b", "c")
}
Result = result
}

benchmark :

go test -run=^$ -bench=. -benchmemgoos: linux
goarch: amd64
pkg: github.com/tkanos/console/escape
BenchmarkCreateKeyString1-8 50000000 26.5 ns/op 8 B/op 1 allocs/op
BenchmarkCreateKeyString2-8 50000000 30.8 ns/op 8 B/op 1 allocs/op
BenchmarkCreateKeyString3-8 50000000 34.0 ns/op 8 B/op 1 allocs/op

Conclusion :

strings.Builder for concatenation is faster, more stable, and allocate less memory.

Special Thanks to dubyte for the review.

--

--