Skip to content

Commit

Permalink
Merge pull request #663 from devlights:add-speeddiff-append-string-to…
Browse files Browse the repository at this point in the history
…-byte-slice

Add speeds for setting strings to byteslice
  • Loading branch information
devlights authored Aug 24, 2023
2 parents 39ebdf5 + cdbb648 commit abddea5
Show file tree
Hide file tree
Showing 3 changed files with 81 additions and 0 deletions.
32 changes: 32 additions & 0 deletions examples/singleapp/speed_diff_append_string_to_byteslice/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# これは何?

バイトスライスに対して

- fmt.Sprintf
- fmt.Appendf
- 直接appendで追加していく

のどれが最も速いのかをベンチマークしてみたものです。

[slogのハンドラ作成ガイドドキュメント](https://github.com/golang/example/blob/master/slog-handler-guide/README.md#speed)に記載があったので試してみました。

以下、Gitpod上で試してみた結果です。

```sh
$ task
goos: linux
goarch: amd64
pkg: github.com/devlights/try-golang/examples/singleapp/speed_diff_append_string_to_byteslice
cpu: AMD EPYC 7B13
BenchmarkUseFmtSprintf-16 3160230 320.0 ns/op
BenchmarkUseFmtAppendf-16 9861033 133.7 ns/op
BenchmarkUseDirectAppend-16 21009861 83.87 ns/op
PASS
ok github.com/devlights/try-golang/examples/singleapp/speed_diff_append_string_to_byteslice 7.914s
```

処理は冗長になってしまいますが、直接appendが最も速いです。

## SeeAlso

- https://gist.github.com/devlights/ffd22f78297a563c9bebcb9a9baa7f5f
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# https://taskfile.dev

version: '3'

tasks:
default:
cmds:
- go test -bench .
silent: true
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
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...) //lint:ignore SA4010 It's ok.
}
}

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:"...) //lint:ignore SA4010 It's ok.
buf = append(buf, strconv.Itoa(i)...) //lint:ignore SA4010 It's ok.
buf = append(buf, '\n') //lint:ignore SA4010 It's ok.
}
}

0 comments on commit abddea5

Please sign in to comment.