In Go, a string
is a primitive type, which means it is read-only, and every manipulation of it will create a new string.
So if I want to concatenate strings many times without knowing the length of the resulting string, what's the best way to do it?
The naive way would be:
s := ""
for i := 0; i < 1000; i++ {
s += getShortStringFromSomewhere()
}
return s
but that does not seem very efficient.
This is the fastest solution that does not require you to know or calculate the overall buffer size first:
By my benchmark, it's 20% slower than the copy solution (8.1ns per append rather than 6.72ns) but still 55% faster than using bytes.Buffer.
benchmark result with memory allocation statistics. check benchmark code at github.
use strings.Builder to optimize performance.
The most efficient way to concatenate strings is using the builtin function
copy
. In my tests, that approach is ~3x faster than usingbytes.Buffer
and much much faster (~12,000x) than using the operator+
. Also, it uses less memory.I've created a test case to prove this and here are the results:
Below is code for testing:
Take a look at the golang's strconv library giving access to several AppendXX functions, enabling us to concatenate strings with strings and other data types.
There is a library function in the strings package called
Join
: http://golang.org/pkg/strings/#JoinA look at the code of
Join
shows a similar approach to Append function Kinopiko wrote: https://golang.org/src/strings/strings.go#L420Usage: