Created
September 23, 2014 20:02
-
-
Save ttacon/7e553087ff0c1d37e310 to your computer and use it in GitHub Desktop.
fmt.Fprint vs bytes.WriteString
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 writestring | |
import ( | |
"bytes" | |
"fmt" | |
"math/rand" | |
"testing" | |
) | |
// go test -bench=. -benchtime 20s | |
// | |
// Benchmark_Fmt 100000000 405 ns/op | |
// Benchmark_WriteString 500000000 133 ns/op | |
var letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") | |
func randSeq(n int) string { | |
b := make([]rune, n) | |
for i := range b { | |
b[i] = letters[rand.Intn(len(letters))] | |
} | |
return string(b) | |
} | |
func Benchmark_Fmt(b *testing.B) { | |
var str = randSeq(rand.Intn(50)) | |
var buf *bytes.Buffer = bytes.NewBuffer(nil) | |
for i := 0; i < b.N; i++ { | |
buf = bytes.NewBuffer(nil) | |
fmt.Fprint(buf, str) | |
} | |
} | |
func Benchmark_WriteString(b *testing.B) { | |
var str = randSeq(rand.Intn(50)) | |
var buf *bytes.Buffer = bytes.NewBuffer(nil) | |
for i := 0; i < b.N; i++ { | |
buf = bytes.NewBuffer(nil) | |
buf.WriteString(str) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment