Skip to content

Instantly share code, notes, and snippets.

@nasa9084
Created May 30, 2019 04:05
Show Gist options
  • Save nasa9084/b2a54bec49bf4ede3b453e8b224ea3b8 to your computer and use it in GitHub Desktop.
Save nasa9084/b2a54bec49bf4ede3b453e8b224ea3b8 to your computer and use it in GitHub Desktop.
Joining strings with + is faster than fmt.Sprintf
package benchmark_test
import (
"fmt"
"strconv"
"testing"
)
var label = "FOOBARBAZ"
func BenchmarkWithSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = fmt.Sprintf("%d/%s", i, label)
}
}
func BenchmarkWithPlus(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = strconv.Itoa(i) + "/" + label
}
}
/* RESULT
$ go test -bench . -benchmem
goos: darwin
goarch: amd64
pkg: practice/go-benchmark
BenchmarkWithSprintf-8 10000000 147 ns/op 54 B/op 3 allocs/op
BenchmarkWithPlus-8 30000000 43.8 ns/op 7 B/op 0 allocs/op
PASS
ok practice/go-benchmark 2.986s
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment