- https://github.com/golang/example/blob/master/slog-handler-guide/README.md#speed
- https://go.dev/blog/slog
package main
import (
"fmt"
"strconv"
"testing"
)
func BenchmarkUseFmtSprintf(b *testing.B) {
b.StopTimer()
buf := make([]byte, 0, 1024*1024*500)
b.StartTimer()
for i := 0; i < b.N; i++ {
s := fmt.Sprintf("%s:%d\n", "key", i)
buf = append(buf, s...)
}
}
func BenchmarkUseFmtAppendf(b *testing.B) {
b.StopTimer()
buf := make([]byte, 0, 1024*1024*500)
b.StartTimer()
for i := 0; i < b.N; i++ {
buf = fmt.Appendf(buf, "%s:%d\n", "key", i)
}
}
func BenchmarkUseDirectAppend(b *testing.B) {
b.StopTimer()
buf := make([]byte, 0, 1024*1024*500)
b.StartTimer()
for i := 0; i < b.N; i++ {
buf = append(buf, "key:"...)
buf = append(buf, strconv.Itoa(i)...)
buf = append(buf, '\n')
}
}
$ go test -bench .
goos: linux
goarch: amd64
pkg: app
cpu: Intel(R) Core(TM) i7-10510U CPU @ 1.80GHz
BenchmarkUseFmtSprintf-8 8510988 128.6 ns/op
BenchmarkUseFmtAppendf-8 11156458 102.0 ns/op
BenchmarkUseDirectAppend-8 35182670 32.80 ns/op
PASS
ok app 4.130s
確かに BenchmarkUseDirectAppend がダントツで速い