Skip to content

Instantly share code, notes, and snippets.

@dustin
Last active December 19, 2015 09:59
Show Gist options
  • Select an option

  • Save dustin/5937001 to your computer and use it in GitHub Desktop.

Select an option

Save dustin/5937001 to your computer and use it in GitHub Desktop.
Measuring `io.Writer` vs. `io.ReaderFrom`
BenchmarkNaiveWriter 10000000 157 ns/op 425060032.69 MB/s
BenchmarkAwesomeWriter 500 5721802 ns/op 11728.62 MB/s
BenchmarkDiscard 500 5735134 ns/op 11701.36 MB/s
package main
import (
"bytes"
"io"
"io/ioutil"
"testing"
)
const todo = 64 * 1024 * 1024
type naiveWriter struct {
o io.Writer
}
func (nw naiveWriter) Write(b []byte) (int, error) {
return nw.o.Write(b)
}
type awesomeWriter struct {
o io.Writer
}
func (aw awesomeWriter) Write(b []byte) (int, error) {
return aw.o.Write(b)
}
func (aw awesomeWriter) ReadFrom(r io.Reader) (int64, error) {
if rf, ok := aw.o.(io.ReaderFrom); ok {
return rf.ReadFrom(r)
}
return io.Copy(aw.o, r)
}
func bench(b *testing.B, w io.Writer) {
b.StopTimer()
data := make([]byte, todo)
b.SetBytes(todo)
b.StartTimer()
for i := 0; i < b.N; i++ {
n, err := io.Copy(w, bytes.NewReader(data))
if err != nil {
b.Fatalf("Error copying: %v", err)
}
if n != todo {
b.Fatalf("Didn't copy enough byte: %v / %v", n, todo)
}
}
}
func BenchmarkNaiveWriter(b *testing.B) {
bench(b, &naiveWriter{ioutil.Discard})
}
func BenchmarkAwesomeWriter(b *testing.B) {
bench(b, &awesomeWriter{ioutil.Discard})
}
func BenchmarkDiscard(b *testing.B) {
bench(b, ioutil.Discard)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment