Skip to content

Instantly share code, notes, and snippets.

@daniellowtw
Created September 14, 2021 16:05
Show Gist options
  • Save daniellowtw/496994cd294cb0485489917474fb6362 to your computer and use it in GitHub Desktop.
Save daniellowtw/496994cd294cb0485489917474fb6362 to your computer and use it in GitHub Desktop.
String append vs string builder vs bytes buffer
package main
import (
"bytes"
"strings"
"testing"
)
func BenchmarkStringAppend(b *testing.B) {
for i := 0; i < b.N; i++ {
f()
}
}
func BenchmarkStringBuilder(b *testing.B) {
for i := 0; i < b.N; i++ {
g()
}
}
func BenchmarkBytesBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
h()
}
}
func h() string {
var s bytes.Buffer
s.WriteString("foo")
s.WriteString("bar")
s.WriteString("car")
return s.String()
}
func f() string {
var s string
s += "foo"
s += "bar"
s += "car"
return s
}
func g() string {
var sb strings.Builder
sb.WriteString("foo")
sb.WriteString("bar")
sb.WriteString("car")
return sb.String()
}
goos: darwin
goarch: amd64
pkg: scratch
cpu: Intel(R) Core(TM) i9-9880H CPU @ 2.30GHz
BenchmarkStringAppend-16 10825950 96.49 ns/op
BenchmarkStringBuilder-16 20359875 65.87 ns/op
BenchmarkBytesBuffer-16 13561768 82.57 ns/op
PASS
ok scratch 4.470s
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment