Skip to content

Instantly share code, notes, and snippets.

@ttacon
Created September 23, 2014 20:02
Show Gist options
  • Save ttacon/7e553087ff0c1d37e310 to your computer and use it in GitHub Desktop.
Save ttacon/7e553087ff0c1d37e310 to your computer and use it in GitHub Desktop.
fmt.Fprint vs bytes.WriteString
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