Skip to content

Instantly share code, notes, and snippets.

@hnakamur
Created October 3, 2019 09:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hnakamur/a3cc6567fe69cf0b7669f862a2043d96 to your computer and use it in GitHub Desktop.
Save hnakamur/a3cc6567fe69cf0b7669f862a2043d96 to your computer and use it in GitHub Desktop.
Go benchmark StringBuilder with Fprintf
package main
import (
"fmt"
"strconv"
"strings"
"testing"
)
func dummy(s string) {}
func BenchmarkStringBuilder(b *testing.B) {
for i := 0; i < b.N; i++ {
var b strings.Builder
b.WriteString("a=")
fmt.Fprintf(&b, "%d", 12345)
dummy(b.String())
}
}
func BenchmarkByteSlice(b *testing.B) {
for i := 0; i < b.N; i++ {
var b []byte
b = append(b, "a="...)
b = strconv.AppendInt(b, 12345, 10)
dummy(string(b))
}
}
func BenchmarkStringList(b *testing.B) {
for i := 0; i < b.N; i++ {
var b []string
b = append(b, "a=")
b = append(b, fmt.Sprintf("%d", 12345))
dummy(strings.Join(b, ""))
}
}
@hnakamur
Copy link
Author

hnakamur commented Oct 3, 2019

$ go test -bench . -benchmem | tee bench.txt
goos: linux
goarch: amd64
BenchmarkStringBuilder-2         7166857               164 ns/op              40 B/op          2 allocs/op
BenchmarkByteSlice-2            24701048                48.5 ns/op             8 B/op          1 allocs/op
BenchmarkStringList-2            4430044               271 ns/op              64 B/op          4 allocs/op
PASS
$ go version
go version go1.13.1 linux/amd64

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