Skip to content

Instantly share code, notes, and snippets.

@tysonmote
Last active August 29, 2015 14:01
Show Gist options
  • Save tysonmote/11200ef28e1b9d93c155 to your computer and use it in GitHub Desktop.
Save tysonmote/11200ef28e1b9d93c155 to your computer and use it in GitHub Desktop.
// BenchmarkBytesBufferNoReuse 2000000 790 ns/op 152 B/op 6 allocs/op
// BenchmarkBytesBufferWithReuse 5000000 675 ns/op 40 B/op 5 allocs/op
// BenchmarkBufioWriterNoReuse 1000000 2273 ns/op 4200 B/op 7 allocs/op
// BenchmarkBufioWriterWithReuse 5000000 541 ns/op 40 B/op 5 allocs/op
// BenchmarkFmt 1000000 1894 ns/op 176 B/op 5 allocs/op
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"strconv"
"testing"
)
var (
LINE_ENDING = []byte{'\r', '\n'}
)
type NoopWriter struct{}
func (w *NoopWriter) Write(p []byte) (int, error) {
return len(p), nil
}
func bufWrite(buf *bytes.Buffer, out io.Writer, args ...string) {
buf.WriteByte('*')
buf.WriteString(strconv.Itoa(len(args)))
buf.Write(LINE_ENDING)
for _, arg := range args {
buf.WriteByte('$')
buf.WriteString(strconv.Itoa(len(arg)))
buf.Write(LINE_ENDING)
buf.WriteString(arg)
buf.Write(LINE_ENDING)
}
buf.WriteTo(out)
}
func bufioWriter(buf *bufio.Writer, args ...string) {
buf.WriteByte('*')
buf.WriteString(strconv.Itoa(len(args)))
buf.Write(LINE_ENDING)
for _, arg := range args {
buf.WriteByte('$')
buf.WriteString(strconv.Itoa(len(arg)))
buf.Write(LINE_ENDING)
buf.WriteString(arg)
buf.Write(LINE_ENDING)
}
buf.Flush()
}
func fmtWrite(args ...string) {
var buf bytes.Buffer
fmt.Fprintf(&buf, "*%d\r\n", len(args))
for _, arg := range args {
fmt.Fprintf(&buf, "$%d\r\n%s\r\n", len(arg), arg)
}
}
func BenchmarkBytesBufferNoReuse(b *testing.B) {
socket := &NoopWriter{}
for i := 0; i < b.N; i++ {
var buf bytes.Buffer
bufWrite(&buf, socket, "foo", "bar", "baz", "biz")
}
}
func BenchmarkBytesBufferWithReuse(b *testing.B) {
socket := &NoopWriter{}
var buf bytes.Buffer
for i := 0; i < b.N; i++ {
bufWrite(&buf, socket, "foo", "bar", "baz", "biz")
buf.Reset()
}
}
func BenchmarkBufioWriterNoReuse(b *testing.B) {
socket := &NoopWriter{}
for i := 0; i < b.N; i++ {
buf := bufio.NewWriter(socket)
bufioWriter(buf, "foo", "bar", "baz", "biz")
}
}
func BenchmarkBufioWriterWithReuse(b *testing.B) {
socket := &NoopWriter{}
buf := bufio.NewWriter(socket)
for i := 0; i < b.N; i++ {
bufioWriter(buf, "foo", "bar", "baz", "biz")
}
}
func BenchmarkFmt(b *testing.B) {
for i := 0; i < b.N; i++ {
fmtWrite("foo", "bar", "baz", "biz")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment