Skip to content

Instantly share code, notes, and snippets.

@atotto
Last active December 16, 2015 14:59
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save atotto/5452948 to your computer and use it in GitHub Desktop.
package stringbuild_test
import (
"bytes"
"testing"
)
func StringBuild_bad() string {
str := ""
for i := 0; i < 1000; i++ {
str += "a"
}
return str
}
func StringBuild_good() string {
var buffer bytes.Buffer
for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}
return buffer.String()
}
func StringBuild_good2() string {
buffer := bytes.NewBufferString("")
for i := 0; i < 1000; i++ {
buffer.WriteString("a")
}
return buffer.String()
}
func BenchmarkStringBuild_bad(b *testing.B) {
for i := 0; i < b.N; i++ {
StringBuild_bad()
}
}
func BenchmarkStringBuild_good(b *testing.B) {
for i := 0; i < b.N; i++ {
StringBuild_good()
}
}
func BenchmarkStringBuild_good2(b *testing.B) {
for i := 0; i < b.N; i++ {
StringBuild_good2()
}
}
/* result
$ go version
go version devel +2a50b4f1d9f9 Sat Apr 13 23:09:08 2013 -0700 darwin/amd64
$ go test -test.bench Bench -test.benchmem
testing: warning: no tests to run
PASS
BenchmarkStringBuild_bad 10000 284844 ns/op 545081 B/op 1000 allocs/op
BenchmarkStringBuild_good 50000 34119 ns/op 3341 B/op 6 allocs/op
ok github.com/atotto/tmp 4.965s
*/
@atotto
Copy link
Author

atotto commented Apr 26, 2013

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