How to concatenate strings efficiently in Go

1. Concatenation using +

foobar := "foo" + "bar"

2. Concatenation using strings.Builder

var sb strings.Builder
sb.WriteString("foo")
sb.WriteString("bar")
// sb.String()

3. Concatenation using bytes.Buffer

var bb bytes.Buffer
bb.WriteString("foo")
bb.WriteString("bar")
// bb.String()

Create the functions

func StringConcatWithAdd() string {
var s string
for i := 0; i < 100; i++ {
s = s + "x"
}

return s
}

func StringConcatWithStringsBuilder() string {
var sb strings.Builder
for i := 0; i < 100; i++ {
sb.WriteString("x")
}

return sb.String()
}

func StringConcatWithBytesBuffer() string {
var bb bytes.Buffer
for i := 0; i < 100; i++ {
bb.WriteString("x")
}

return bb.String()
}

Preparing for the benchmark

func BenchmarkStringConcatWithAdd(b *testing.B) {
b.ReportAllocs()

for i := 0; i < b.N; i++ {
strconcat.StringConcatWithAdd()
}
}

func BenchmarkStringConcatWithStringsBuilder(b *testing.B) {
b.ReportAllocs()

for i := 0; i < b.N; i++ {
strconcat.StringConcatWithStringsBuilder()
}
}

func BenchmarkStringConcatWithBytesBuffer(b *testing.B) {
b.ReportAllocs()

for i := 0; i < b.N; i++ {
strconcat.StringConcatWithBytesBuffer()
}
}

The results

BenchmarkStringConcatWithAdd
BenchmarkStringConcatWithAdd-8 252232 4709 ns/op 5728 B/op 99 allocs/op
BenchmarkStringConcatWithStringsBuilder
BenchmarkStringConcatWithStringsBuilder-8 3282949 363 ns/op 248 B/op 5 allocs/op
BenchmarkStringConcatWithBytesBuffer
BenchmarkStringConcatWithBytesBuffer-8 1545480 825 ns/op 320 B/op 3 allocs/op

Conclusion

--

--

--

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Join the Lightweight Java User Group München online (May 5th)

9 Steps to Connect Database to Laravel

Where is the magic thread in asynchronous code?

Load scenes in Unity

You Can Make A Hit App Without Coding | Tips from Colin Lane

Rules You Should Follow When Building Web Apps

Phase I — Progress report — Health pickup

Anomaly Detection using Kinesis and Spark Streaming

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Daryl Ng

Daryl Ng

More from Medium

GO 101 — Go Basics(Chapter 1)

How To Upgrade An Indirect Dependency In GoLang

Dependency Injection in Go

Do You Need A Implementation Jwt In Go (Golang)?