Skip to content

Instantly share code, notes, and snippets.

@imjasonh
Last active October 28, 2021 06:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save imjasonh/da090817f7d513441d09 to your computer and use it in GitHub Desktop.
Save imjasonh/da090817f7d513441d09 to your computer and use it in GitHub Desktop.
$ go test -bench=.
testing: warning: no tests to run
PASS
BenchmarkBuffer 100 14674718 ns/op
BenchmarkPipe 100 14456488 ns/op
package pipe
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"testing"
)
const dataSize = 10000
func BenchmarkBuffer(b *testing.B) {
m := makeData()
for i := 0; i < b.N; i++ {
var buf bytes.Buffer
_ = json.NewEncoder(&buf).Encode(m)
_, _ = io.Copy(ioutil.Discard, &buf)
}
}
func BenchmarkPipe(b *testing.B) {
m := makeData()
for i := 0; i < b.N; i++ {
pr, pw := io.Pipe()
go func() {
pw.CloseWithError(json.NewEncoder(pw).Encode(m))
}()
_, _ = io.Copy(ioutil.Discard, pr)
}
}
func makeData() map[string]string {
m := map[string]string{}
for i := 0; i < dataSize; i++ {
m[fmt.Sprintf("key-%d", i)] = fmt.Sprintf("val-%d", i)
}
return m
}
@regorov
Copy link

regorov commented Jun 19, 2016

If you move declaration buf bytes.Buffer out of cycle it will change a picture.
If you set dataSize to 10, it will change picture again.
I would stay with bytes.Buffer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment