Skip to content

Instantly share code, notes, and snippets.

@dtjm
Last active November 26, 2023 13:18
Show Gist options
  • Save dtjm/c6ebc86abe7515c988ec to your computer and use it in GitHub Desktop.
Save dtjm/c6ebc86abe7515c988ec to your computer and use it in GitHub Desktop.
Benchmarking various ways of concatenating strings in Go
package join
import (
"fmt"
"strings"
"testing"
)
var (
testData = []string{"a", "b", "c", "d", "e"}
)
func BenchmarkJoin(b *testing.B) {
for i := 0; i < b.N; i++ {
s := strings.Join(testData, ":")
_ = s
}
}
func BenchmarkSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
s := fmt.Sprintf("%s:%s:%s:%s:%s", testData[0], testData[1], testData[2], testData[3], testData[4])
_ = s
}
}
func BenchmarkConcat(b *testing.B) {
for i := 0; i < b.N; i++ {
s := testData[0] + ":" + testData[1] + ":" + testData[2] + ":" + testData[3] + ":" + testData[4]
_ = s
}
}
@GwynethLlewelyn
Copy link

Hm. Seems that concat done in one line might be the winner here: it's the easiest to read, does not allocate anything, and is only beaten by writing to a buffer, which, although being cool as a concept, looks much weirder (especially for someone who comes from other programming languages where string concatenation is simply done with an operator between strings...). I'm sure that there are many special cases where it's worth the extra typing effort to use buffers, but... I'm a big fan of keeping things simple and understandable. If the 'cost' of doing so is just a dozen extra nanoseconds... it's worth the trouble, IMHO.

@lovung
Copy link

lovung commented Sep 9, 2021

Use the code from @RezaOptic above

go version go1.17 darwin/amd64

Results

goos: darwin
goarch: amd64
pkg: ***
cpu: Intel(R) Core(TM) i7-4980HQ CPU @ 2.80GHz
BenchmarkJoin-8                  	18044035	        74.59 ns/op	      16 B/op	       1 allocs/op
BenchmarkSprintf-8               	 3249290	       393.9 ns/op	      96 B/op	       6 allocs/op
BenchmarkConcat-8                	 6670018	       257.7 ns/op	      32 B/op	       4 allocs/op
BenchmarkConcatOneLine-8         	20360762	        94.10 ns/op	       0 B/op	       0 allocs/op
BenchmarkBuffer-8                	16493529	       102.2 ns/op	      64 B/op	       1 allocs/op
BenchmarkBufferWithReset-8       	29284802	        51.32 ns/op	       0 B/op	       0 allocs/op
BenchmarkBufferFprintf-8         	 2917341	       392.3 ns/op	      80 B/op	       5 allocs/op
BenchmarkBufferStringBuilder-8   	15469124	        93.51 ns/op	      24 B/op	       2 allocs/op

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment