Concatenating Strings in Go Efficiently
It's common to concatenate a series of strings to a target string. In Go, we can do it simply by:
func concatenate() string {
target := ""
strings := []string{"foo", "bar", "baz"}
for _, string := range strings {
target += string
}
return target
}
However, It can be taken to another level for better performance. We use bytes
package to create a buffer, and then write every string to it before we return it as a String
.
import "bytes"
func concatenate() string {
var buffer bytes.Buffer
strings := []string{"foo", "bar", "baz"}
for _, string := range strings {
buffer.WriteString(string)
}
return buffer.String()
}