Concatenate strings in golang a quick benchmark
Introduction
When I begin to enter golang code bases with developer of variou...
For further actions, you may consider blocking this person and/or reporting abuse
Your benchmark is incorrect, the only thing you are measuring is the optimizations of the golang compiler / runtime in simple cases. Here is a slightly improved benchmark that shows how hugely different results you get if you disable golang optimizations (or make it hard for go to optimize your code):
If executed with
go test -gcflags=-N -bench=.
returns the following results:As you can see a Builder is often more than 1000x faster than other approaches.
fmt.Sprintf
andstrings.Join
have about the same speed as+
, but this changes as soon as you do multiple concatenations in a single call:here
strings.Join
will be measurable faster than+
.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.
In my case join wins by a long margin, cant figure out whats wrong.
Join has less allocs as well
On strace: string concatenation isn't a system call. The strace for these programs should be the same as the strace for hello world.
I didn't mean to say that. What made you think this way ? Maybe I Can make my post more clear with your help.
The article is about string concatenation. Why look at strace at all?
It's to explain why C is more efficient than Go, which is no explicitly explained.
I don't agree that a syscall count has anything to do with a languages efficiency compared to another language.
I'll make it more clear.