Skip to content

Instantly share code, notes, and snippets.

@bendrucker
Created February 24, 2023 03:26
Show Gist options
  • Save bendrucker/2d161a34693f5c14bbc493fa950f7e2d to your computer and use it in GitHub Desktop.
Save bendrucker/2d161a34693f5c14bbc493fa950f7e2d to your computer and use it in GitHub Desktop.
Benchmarking string concatenation written to a buffer in Go

This module benchmarks joining 5 strings with colons and writing the resulting string to a buffer. The result shows that concatenating with + is ~3-4x faster and performs fewer allocations. Fprintf and friends require 1 allocation per formatting operator.

golang/go#8618

go test -bench=.
goos: darwin
goarch: arm64
pkg: bench-strings
BenchmarkFprintf-10    	 5534516	       216.9 ns/op	     192 B/op	       7 allocs/op
BenchmarkConcat-10     	19905655	        60.62 ns/op	      64 B/op	       1 allocs/op
PASS
ok  	bench-strings	2.827s
module bench-strings
go 1.19
package main
import (
"bytes"
"fmt"
"testing"
)
var (
testData = []string{"a", "b", "c", "d", "e"}
)
func BenchmarkFprintf(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
buf := &bytes.Buffer{}
fmt.Fprintf(buf, "%s:%s:%s:%s:%s", testData[0], testData[1], testData[2], testData[3], testData[4])
}
}
func BenchmarkConcat(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
buf := &bytes.Buffer{}
buf.WriteString(testData[0] + ":" + testData[1] + ":" + testData[2] + ":" + testData[3] + ":" + testData[4])
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment