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 actual version of benchmark provided by @cd1 (
Go 1.8
,linux x86_64
) with the fixes of bugs mentioned by @icza and @PickBoy.Bytes.Buffer
is only7
times faster than direct string concatenation via+
operator.Timings:
goutils.JoinBetween