DEV Community

Discussion on: Concatenate strings in golang a quick benchmark : + or fmt.Sprintf ?

Collapse
 
bgadrian profile image
Adrian B.G.

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.

Collapse
 
fasmat profile image
Matthias Fasching • Edited

+ 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.

Collapse
 
pmalhaire profile image
pmalhaire

Thanks for your comment I'll update my post accordingly, note that the c version preallocates the buffer.