Skip to content

Instantly share code, notes, and snippets.

@PyYoshi
Last active August 4, 2016 00:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save PyYoshi/5128400f7cfa49eedd5b9b29a98bacd3 to your computer and use it in GitHub Desktop.
Save PyYoshi/5128400f7cfa49eedd5b9b29a98bacd3 to your computer and use it in GitHub Desktop.
package strbench
// Results
// // i7-4650U CPU @ 1.70GHz
//
// go version go1.6.2 darwin/amd64
// BenchmarkAppendStr-4 30000000 41.0 ns/op 0 B/op 0 allocs/op
// BenchmarkFmtFormat-4 5000000 383 ns/op 24 B/op 2 allocs/op
// BenchmarkConcat1-4 5000000 280 ns/op 64 B/op 2 allocs/op
// BenchmarkConcat2-4 3000000 395 ns/op 116 B/op 4 allocs/op
// BenchmarkTemplate-4 1000000 1420 ns/op 88 B/op 5 allocs/op
//
// go version go1.7rc5 darwin/amd64
// BenchmarkAppendStr-4 50000000 31.4 ns/op 0 B/op 0 allocs/op
// BenchmarkFmtFormat-4 5000000 304 ns/op 24 B/op 2 allocs/op
// BenchmarkConcat1-4 5000000 261 ns/op 64 B/op 2 allocs/op
// BenchmarkConcat2-4 5000000 318 ns/op 116 B/op 4 allocs/op
// BenchmarkTemplate-4 1000000 1342 ns/op 88 B/op 5 allocs/op
import (
"fmt"
"strings"
"testing"
"text/template"
)
var bob = &struct {
Name string
Age int
}{
Name: "Bob",
Age: 23,
}
type NullWriter struct{}
func (w *NullWriter) Write(b []byte) (int, error) { return len(b), nil }
func BenchmarkAppendStr(b *testing.B) {
w := &NullWriter{}
buff := []byte{}
for i := 0; i < b.N; i++ {
buff = buff[0:0]
buff = append(buff, "Hi, my name is "...)
buff = append(buff, bob.Name...)
buff = append(buff, " and I'm "...)
buff = append(buff, string(bob.Age)...)
buff = append(buff, " years old."...)
w.Write(buff)
}
}
func BenchmarkFmtFormat(b *testing.B) {
w := &NullWriter{}
for i := 0; i < b.N; i++ {
fmt.Fprintf(w, "Hi, my name is %s and I'm %d years old.", bob.Name, bob.Age)
}
}
func BenchmarkConcat1(b *testing.B) {
w := &NullWriter{}
for i := 0; i < b.N; i++ {
fmt.Fprint(w, "Hi, my name is "+bob.Name+" and I'm "+string(bob.Age)+" years old.")
}
}
func BenchmarkConcat2(b *testing.B) {
w := &NullWriter{}
for i := 0; i < b.N; i++ {
fmt.Fprint(w, strings.Join([]string{"Hi, my name is ", bob.Name, " and I'm ", string(bob.Age), " years old."}, ""))
}
}
func BenchmarkTemplate(b *testing.B) {
t := template.Must(template.New("").Parse(
`Hi, my name is {{.Name}} and I'm {{.Age}} years old.`))
w := &NullWriter{}
for i := 0; i < b.N; i++ {
t.Execute(w, bob)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment