Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link
Owner 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
You can’t perform that action at this time.