Skip to content

Instantly share code, notes, and snippets.

@ktrysmt
Created May 19, 2016 09:10
Show Gist options
  • Save ktrysmt/b870d9d7d7dae2dbbf263def92293e79 to your computer and use it in GitHub Desktop.
Save ktrysmt/b870d9d7d7dae2dbbf263def92293e79 to your computer and use it in GitHub Desktop.
結局Goの文字列結合はどれが一番早いのか
package main
import (
"bytes"
"fmt"
"testing"
)
var m = [...]string{
"AAAAAAAAA",
"AAAAAAAAA",
"AAAAAAAAA",
"AAAAAAAAA",
"AAAAAAAAA",
"AAAAAAAAA",
"AAAAAAAAA",
}
func BenchmarkSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = fmt.Sprintf("%s", m)
}
}
func BenchmarkCapBytesBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
var m2 = bytes.NewBuffer(make([]byte, 0, 100))
for _, v := range m {
m2.WriteString(v)
}
_ = m2.String()
}
}
func BenchmarkCapByteArray(b *testing.B) {
for i := 0; i < b.N; i++ {
var m2 = make([]byte, 0, 100)
for _, v := range m {
m2 = append(m2, v...)
}
_ = string(m2)
}
}
@ktrysmt
Copy link
Author

ktrysmt commented May 19, 2016

手元のMacBookProでとりあえず計測

BenchmarkSprintf         1000000              1479 ns/op
BenchmarkCapBytesBuffer  3000000               420 ns/op
BenchmarkCapByteArray   10000000               188 ns/op
ok      _/tmp/performance-sprintf-vs-bytebuffer 5.248s

BenchmarkSprintf         1000000              1433 ns/op
BenchmarkCapBytesBuffer  3000000               415 ns/op
BenchmarkCapByteArray   10000000               184 ns/op
ok      _/tmp/performance-sprintf-vs-bytebuffer 5.160s

BenchmarkSprintf         1000000              1476 ns/op
BenchmarkCapBytesBuffer  3000000               443 ns/op
BenchmarkCapByteArray   10000000               179 ns/op
ok      _/tmp/performance-sprintf-vs-bytebuffer 5.248s

結果、やっぱりキャパシティ付きのByte型appendが最速

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment