Skip to content

Instantly share code, notes, and snippets.

@yowcow
Created October 16, 2017 02:22
Show Gist options
  • Save yowcow/f6740031991b1117d2ee4d967cb4e15e to your computer and use it in GitHub Desktop.
Save yowcow/f6740031991b1117d2ee4d967cb4e15e to your computer and use it in GitHub Desktop.
Buffer or Buffered IO, multiple times or at once
package main
import (
"bufio"
"bytes"
"fmt"
"io"
"testing"
)
var Space = []byte(" ")
func writeThroughBufferedIO(buf io.Writer) {
w := bufio.NewWriter(buf)
w.WriteString("hoge")
w.WriteRune(' ')
w.WriteString("fuga")
w.WriteRune(' ')
w.WriteString("foo")
w.WriteRune(' ')
w.WriteString("bar")
w.Flush()
}
func Test_writeThroughBufferedIO(t *testing.T) {
buf := new(bytes.Buffer)
writeThroughBufferedIO(buf)
if "hoge fuga foo bar" != buf.String() {
t.Error("expected 'hoge fuga foo bar' but got", buf.String())
}
}
func Benchmark_writeThroughBufferedIO(b *testing.B) {
for i := 0; i < b.N; i++ {
buf := new(bytes.Buffer)
writeThroughBufferedIO(buf)
}
}
func writeToBuffer(buf io.Writer) {
buf.Write([]byte("hoge"))
buf.Write(Space)
buf.Write([]byte("fuga"))
buf.Write(Space)
buf.Write([]byte("foo"))
buf.Write(Space)
buf.Write([]byte("bar"))
}
func Test_writeToBuffer(t *testing.T) {
buf := new(bytes.Buffer)
writeToBuffer(buf)
if "hoge fuga foo bar" != buf.String() {
t.Error("expected 'hoge fuga foo bar' but got", buf.String())
}
}
func Benchmark_writeToBuffer(b *testing.B) {
for i := 0; i < b.N; i++ {
buf := new(bytes.Buffer)
writeToBuffer(buf)
}
}
func writeThroughBufferedIOAtOnce(buf io.Writer) {
w := bufio.NewWriter(buf)
w.WriteString(fmt.Sprintf("%s %s %s %s", "hoge", "fuga", "foo", "bar"))
w.Flush()
}
func Test_writeThroughBufferedIOAtOnce(t *testing.T) {
buf := new(bytes.Buffer)
writeThroughBufferedIOAtOnce(buf)
if "hoge fuga foo bar" != buf.String() {
t.Error("expected 'hoge fuga foo bar' but got", buf.String())
}
}
func Benchmark_writeThroughBufferedIOAtOnce(b *testing.B) {
for i := 0; i < b.N; i++ {
buf := new(bytes.Buffer)
writeThroughBufferedIOAtOnce(buf)
}
}
func writeToBufferAtOnce(buf io.Writer) {
fmt.Fprintf(buf, "%s %s %s %s", "hoge", "fuga", "foo", "bar")
}
func Test_writeToBufferAtOnce(t *testing.T) {
buf := new(bytes.Buffer)
writeToBufferAtOnce(buf)
if "hoge fuga foo bar" != buf.String() {
t.Error("expected 'hoge fuga foo bar' but got", buf.String())
}
}
func Benchmark_writeToBufferAtOnce(b *testing.B) {
for i := 0; i < b.N; i++ {
buf := new(bytes.Buffer)
writeToBufferAtOnce(buf)
}
}
/***
Benchmark_writeThroughBufferedIO-4 2000000 817 ns/op
Benchmark_writeToBuffer-4 10000000 233 ns/op
Benchmark_writeThroughBufferedIOAtOnce-4 1000000 1021 ns/op
Benchmark_writeToBufferAtOnce-4 5000000 239 ns/op
***/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment