-
-
Save AlphaWong/b27de6f64b29088047c792aa5ab779be to your computer and use it in GitHub Desktop.
golang 1.10 strings builder test
This file contains hidden or 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
$ go test -bench . -benchmem | |
goos: linux | |
goarch: amd64 | |
pkg: github.com/knsh14/sample | |
BenchmarkBytesBuffer-2 10 103512777 ns/op 438779214 B/op 23 allocs/op | |
BenchmarkStringBuilder-2 10 138950789 ns/op 661977072 B/op 54 allocs/op | |
BenchmarkBytesBufferString-2 5000000 353 ns/op 1280 B/op 1 allocs/op | |
BenchmarkStringBuilderString-2 2000000000 0.33 ns/op 0 B/op 0 allocs/op | |
PASS | |
ok github.com/knsh14/sample 5.699s |
This file contains hidden or 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 main | |
import ( | |
"bytes" | |
"strings" | |
) | |
func BytesBuffer() string { | |
var out bytes.Buffer | |
for i := 0; i < 1000000; i++ { | |
out.WriteString("hello world\n") | |
} | |
return out.String() | |
} | |
func StringBuilder() string { | |
var out strings.Builder | |
for i := 0; i < 1000000; i++ { | |
out.WriteString("hello world\n") | |
} | |
return out.String() | |
} | |
func NewBytesBuffer() bytes.Buffer { | |
var out bytes.Buffer | |
for i := 0; i < 100; i++ { | |
out.WriteString("hello world\n") | |
} | |
return out | |
} | |
func NewStringBuilder() strings.Builder { | |
var out strings.Builder | |
for i := 0; i < 100; i++ { | |
out.WriteString("hello world\n") | |
} | |
return out | |
} |
This file contains hidden or 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 main | |
import "testing" | |
func BenchmarkBytesBuffer(b *testing.B) { | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = BytesBuffer() | |
} | |
} | |
func BenchmarkStringBuilder(b *testing.B) { | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = StringBuilder() | |
} | |
} | |
func BenchmarkBytesBufferString(b *testing.B) { | |
v := NewBytesBuffer() | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = v.String() | |
} | |
} | |
func BenchmarkStringBuilderString(b *testing.B) { | |
v := NewStringBuilder() | |
b.ResetTimer() | |
for i := 0; i < b.N; i++ { | |
_ = v.String() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment