Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
package main
import (
"bytes"
"fmt"
"strconv"
"sync"
"testing"
)
func BenchmarkSprintf(b *testing.B) {
for i := 0; i < b.N; i++ {
_ = fmt.Sprintf("[%d] %s <%s>\n", i, "Sergio", "sergio@example.com")
}
}
func BenchmarkBuffer(b *testing.B) {
pool := sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
for i := 0; i < b.N; i++ {
buf := pool.Get().(*bytes.Buffer)
buf.WriteString("[")
buf.WriteString(strconv.Itoa(i))
buf.WriteString("] ")
buf.WriteString("Sergio")
buf.WriteString(" <")
buf.WriteString("sergio@example.com")
buf.WriteString(">\n")
buf.Reset()
pool.Put(buf)
}
}
//BenchmarkSprintf-8 10000000 184 ns/op 56 B/op 2 allocs/op
//BenchmarkBuffer-8 20000000 93.6 ns/op 7 B/op 0 allocs/op
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment