Striving to become a master Go/Cloud developer; Father ๐จโ๐งโ๐ฆ; ๐ค/((Full Stack Web|Unity3D) + Developer)/g; Science supporter ๐ฉโ๐ฌ; https://coder.today
I tried to do this micro optimization a few months ago and kinda failed.
The recommended way is to use strings.Builder. As I did not knew the string size a simple + worked better in benchmarks (at least for strings less than ~20 characters.
I ended up approximating the result (and pre allocate memory with a buffer) and got the best result, but most of the times + is the best choice.
+ will always be the slowest way to concatenate strings.
In simple cases (concatenate only exactly 2 strings) every other method: builder, join, and sprintf will be ~ the same speed as +.
The benchmark here is just incorrect. Because the resulting string in the Plus tests isn't assigned to anything the compiler just makes it a NOP before executing the tests.
Run the benchmarks again and disable optimizations (go test -gcflags=-N -bench=.) and you will see that all methods have ~ the same execution time. In cases where you concatenate more than 2 strings + will always be the slowest (and most memory hungry) method.
I tried to do this micro optimization a few months ago and kinda failed.
The recommended way is to use
strings.Builder
. As I did not knew the string size a simple+
worked better in benchmarks (at least for strings less than ~20 characters.I ended up approximating the result (and pre allocate memory with a buffer) and got the best result, but most of the times
+
is the best choice.+
will always be the slowest way to concatenate strings.In simple cases (concatenate only exactly 2 strings) every other method: builder, join, and sprintf will be ~ the same speed as +.
The benchmark here is just incorrect. Because the resulting string in the Plus tests isn't assigned to anything the compiler just makes it a NOP before executing the tests.
Run the benchmarks again and disable optimizations (
go test -gcflags=-N -bench=.
) and you will see that all methods have ~ the same execution time. In cases where you concatenate more than 2 strings+
will always be the slowest (and most memory hungry) method.Thanks for your comment I'll update my post accordingly, note that the c version preallocates the buffer.