Skip to content

Instantly share code, notes, and snippets.

@bardex
Last active November 3, 2021 02:46
Show Gist options
  • Save bardex/191c0ff6759e55596b5528c0253111cf to your computer and use it in GitHub Desktop.
Save bardex/191c0ff6759e55596b5528c0253111cf to your computer and use it in GitHub Desktop.
Benchmarks for joining string from small chunks in golang
package bench
import (
"fmt"
"strconv"
"strings"
"testing"
)
var validResult = "100 abc --- false 200 500"
func BenchmarkConcat(b *testing.B) {
for i := 0; i < b.N; i++ {
a := 100
g := "abc"
c := "---"
d := "false"
e := 200
f := "500"
result := strconv.Itoa(a) + " " + g + " " + c + " " + d + " " + strconv.Itoa(e) + " " + f
if result != validResult {
b.Fatalf("%s <> %s", result, validResult)
}
}
}
func BenchmarkJoin(b *testing.B) {
for i := 0; i < b.N; i++ {
chunks := []string{
strconv.Itoa(100),
"abc",
"---",
"false",
strconv.Itoa(200),
"500",
}
result := strings.Join(chunks, " ")
if result != validResult {
b.Fatalf("%s <> %s", result, validResult)
}
}
}
func BenchmarkBuilder(b *testing.B) {
for i := 0; i < b.N; i++ {
builder := strings.Builder{}
builder.WriteString(strconv.Itoa(100))
builder.WriteString(" ")
builder.WriteString("abc")
builder.WriteString(" ")
builder.WriteString("---")
builder.WriteString(" ")
builder.WriteString("false")
builder.WriteString(" ")
builder.WriteString(strconv.Itoa(200))
builder.WriteString(" ")
builder.WriteString("500")
result := builder.String()
if result != validResult {
b.Fatalf("%s <> %s", result, validResult)
}
}
}
func BenchmarkSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
a := 100
g := "abc"
c := "---"
d := "false"
e := 200
f := "500"
result := fmt.Sprintf("%d %s %s %s %d %s", a, g, c, d, e, f)
if result != validResult {
b.Fatalf("%s <> %s", result, validResult)
}
}
}
/*
go test -bench=. -benchmem concat_test.go
goos: linux
goarch: amd64
cpu: Intel(R) Core(TM) i7-6700T CPU @ 2.80GHz
BenchmarkConcat-8 6188331 196.0 ns/op 38 B/op 3 allocs/op
BenchmarkJoin-8 6894038 174.2 ns/op 38 B/op 3 allocs/op
BenchmarkBuilder-8 6189663 188.7 ns/op 64 B/op 5 allocs/op
BenchmarkSprintf-8 2614960 468.2 ns/op 96 B/op 5 allocs/op
PASS
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment