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.
My original suggestion was
But above answer using bytes.Buffer - WriteString() is the most efficient way.
My initial suggestion uses reflection and a type switch. See
(p *pp) doPrint
and(p *pp) printArg
There is no universal Stringer() interface for basic types, as I had naively thought.
At least though, Sprint() internally uses a bytes.Buffer. Thus
is acceptable in terms of memory allocations.
=> Sprint() concatenation can be used for quick debug output.
=> Otherwise use bytes.Buffer ... WriteString
Note added in 2018
From Go 1.10 there is the strings.Builder type, which achieves this even more efficiently (for strings). The example given there is succinct and easy to copy/adapt.
Please take a look at this answer for more detail
For the benchmark of strings.Builder, take a look at this answer
Pre-201x answer
The best way is to use the
bytes
package. It has aBuffer
type which implementsio.Writer
.This does it in O(n) time.
I do it using the following :-
For those who come from the Java world where we have
StringBuilder
for efficient string concatenation, it seems like the latest go version has its equivalent and it's calledBuilder
: https://github.com/golang/go/blob/master/src/strings/builder.goExpanding on cd1's answer: You might use append() instead of copy(). append() makes ever bigger advance provisions, costing a little more memory, but saving time. I added two more benchmarks at the top of yours. Run locally with
On my thinkpad T400s it yields: