Why you should avoid ioutil.ReadAll in Go

func IOUtilReadAll(reader io.Reader) (map[string]interface{}, error) {
var (
m map[string]interface{}
b, _ = ioutil.ReadAll(reader)
)

return m, json.Unmarshal(b, &m)
}
func IOCopy(reader io.Reader) (map[string]interface{}, error) {
var (
m map[string]interface{}
buf bytes.Buffer
_, _ = io.Copy(&buf, reader)
)

return m, json.Unmarshal(buf.Bytes(), &m)
}
func JsonDecoder(reader io.Reader) (map[string]interface{}, error) {
var m map[string]interface{}

return m, json.NewDecoder(reader).Decode(&m)
}
var jsonStr = `{"one":"foobar","two":"foobar","three":"foobar","four":"foobar","five":"foobar","six":"foobar","seven":"foobar","eight":"foobar","nine":"foobar","ten":"foobar"}`func BenchmarkJsonDecoder(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
JsonDecoder(strings.NewReader(jsonStr))
}
}

func BenchmarkIOUtilReadAll(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
IOUtilReadAll(strings.NewReader(jsonStr))
}
}

func BenchmarkIOCopy(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
IOCopy(strings.NewReader(jsonStr))
}
}
BenchmarkJsonDecoder
BenchmarkJsonDecoder-8 180230 6741 ns/op 2766 B/op 69 allocs/op
BenchmarkIOUtilReadAll
BenchmarkIOUtilReadAll-8 168019 6928 ns/op 4126 B/op 69 allocs/op
BenchmarkIOCopy
BenchmarkIOCopy-8 158901 6677 ns/op 2286 B/op 69 allocs/op

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store