Last active
December 16, 2015 14:59
-
-
Save atotto/5452948 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Blog : http://atotto.hatenadiary.jp/entry/2013/04/26/202701