Skip to content

Instantly share code, notes, and snippets.

@devlights
Last active August 23, 2023 08:04
Show Gist options
  • Save devlights/ffd22f78297a563c9bebcb9a9baa7f5f to your computer and use it in GitHub Desktop.
Save devlights/ffd22f78297a563c9bebcb9a9baa7f5f to your computer and use it in GitHub Desktop.
バイトスライスに文字列を速く設定する方法(fmt.Sprintf, fmt.Appendf, 直接append使用)

バイトスライスに文字列を速く設定する方法(fmt.Sprintf, fmt.Appendf, 直接append使用)

参考

試してみた

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 がダントツで速い

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')
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment