Last active
October 28, 2021 06:15
-
-
Save imjasonh/da090817f7d513441d09 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ go test -bench=. | |
testing: warning: no tests to run | |
PASS | |
BenchmarkBuffer 100 14674718 ns/op | |
BenchmarkPipe 100 14456488 ns/op |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.