Skip to content

Instantly share code, notes, and snippets.

@mark-rushakoff
Created December 19, 2015 18:48
Show Gist options
  • Save mark-rushakoff/1c4c9123a840be787e38 to your computer and use it in GitHub Desktop.
Save mark-rushakoff/1c4c9123a840be787e38 to your computer and use it in GitHub Desktop.
Which is faster: `s += str` or `buf.WriteString(str) ... buf.String()`?
PASS
BenchmarkStringConcat-4 2000000 3901 ns/op
BenchmarkByteBuffer-4 10000000 966 ns/op
package strings_test
import (
"bytes"
"testing"
)
import "strings"
var alphabet = strings.Split("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ", "")
var result string
func TestNothing(t *testing.T) {}
func BenchmarkStringConcat(b *testing.B) {
for i := 0; i < b.N; i++ {
s := ""
for _, c := range alphabet {
s += c
}
result = s
}
if result != strings.Join(alphabet, "") {
b.Fatalf("bug")
}
}
func BenchmarkByteBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
var b bytes.Buffer
for _, c := range alphabet {
_, _ = b.WriteString(c)
}
result = b.String()
}
if result != strings.Join(alphabet, "") {
b.Fatalf("bug")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment