File tree Expand file tree Collapse file tree 3 files changed +81
-0
lines changed
examples/singleapp/speed_diff_append_string_to_byteslice Expand file tree Collapse file tree 3 files changed +81
-0
lines changed Original file line number Diff line number Diff line change 1+ # これは何?
2+
3+ バイトスライスに対して
4+
5+ - fmt.Sprintf
6+ - fmt.Appendf
7+ - 直接appendで追加していく
8+
9+ のどれが最も速いのかをベンチマークしてみたものです。
10+
11+ [ slogのハンドラ作成ガイドドキュメント] ( https://github.com/golang/example/blob/master/slog-handler-guide/README.md#speed ) に記載があったので試してみました。
12+
13+ 以下、Gitpod上で試してみた結果です。
14+
15+ ``` sh
16+ $ task
17+ goos: linux
18+ goarch: amd64
19+ pkg: github.com/devlights/try-golang/examples/singleapp/speed_diff_append_string_to_byteslice
20+ cpu: AMD EPYC 7B13
21+ BenchmarkUseFmtSprintf-16 3160230 320.0 ns/op
22+ BenchmarkUseFmtAppendf-16 9861033 133.7 ns/op
23+ BenchmarkUseDirectAppend-16 21009861 83.87 ns/op
24+ PASS
25+ ok github.com/devlights/try-golang/examples/singleapp/speed_diff_append_string_to_byteslice 7.914s
26+ ```
27+
28+ 処理は冗長になってしまいますが、直接appendが最も速いです。
29+
30+ ## SeeAlso
31+
32+ - https://gist.github.com/devlights/ffd22f78297a563c9bebcb9a9baa7f5f
Original file line number Diff line number Diff line change 1+ # https://taskfile.dev
2+
3+ version : ' 3'
4+
5+ tasks :
6+ default :
7+ cmds :
8+ - go test -bench .
9+ silent : true
Original file line number Diff line number Diff line change 1+ package main
2+
3+ import (
4+ "fmt"
5+ "strconv"
6+ "testing"
7+ )
8+
9+ func BenchmarkUseFmtSprintf (b * testing.B ) {
10+ b .StopTimer ()
11+ buf := make ([]byte , 0 , 1024 * 1024 * 500 )
12+ b .StartTimer ()
13+
14+ for i := 0 ; i < b .N ; i ++ {
15+ s := fmt .Sprintf ("%s:%d\n " , "key" , i )
16+ buf = append (buf , s ... ) //lint:ignore SA4010 It's ok.
17+ }
18+ }
19+
20+ func BenchmarkUseFmtAppendf (b * testing.B ) {
21+ b .StopTimer ()
22+ buf := make ([]byte , 0 , 1024 * 1024 * 500 )
23+ b .StartTimer ()
24+
25+ for i := 0 ; i < b .N ; i ++ {
26+ buf = fmt .Appendf (buf , "%s:%d\n " , "key" , i )
27+ }
28+ }
29+
30+ func BenchmarkUseDirectAppend (b * testing.B ) {
31+ b .StopTimer ()
32+ buf := make ([]byte , 0 , 1024 * 1024 * 500 )
33+ b .StartTimer ()
34+
35+ for i := 0 ; i < b .N ; i ++ {
36+ buf = append (buf , "key:" ... ) //lint:ignore SA4010 It's ok.
37+ buf = append (buf , strconv .Itoa (i )... ) //lint:ignore SA4010 It's ok.
38+ buf = append (buf , '\n' ) //lint:ignore SA4010 It's ok.
39+ }
40+ }
You can’t perform that action at this time.
0 commit comments