DEV Community

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

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.