From 3c783b99fa0bf68bd6acae5f316c2d512d93dc1e Mon Sep 17 00:00:00 2001 From: Steven Allen Date: Tue, 4 Aug 2020 21:57:29 -0700 Subject: [PATCH] Optimize readByte Type asserting to a concrete type is ~10x faster than type asserting to an interface. This change has a significant performance impact in my test. readByte used to account for 10.8% of the time, now it accounts for 3.4%. --- utils.go | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) diff --git a/utils.go b/utils.go index b2496c8..4e3aacf 100644 --- a/utils.go +++ b/utils.go @@ -1,6 +1,8 @@ package typegen import ( + "bufio" + "bytes" "encoding/binary" "errors" "fmt" @@ -202,8 +204,19 @@ func (d *Deferred) UnmarshalCBOR(br io.Reader) error { } func readByte(r io.Reader) (byte, error) { - if br, ok := r.(io.ByteReader); ok { - return br.ReadByte() + // try to cast to a concrete type, it's much faster than casting to an + // interface. + switch r := r.(type) { + case *bytes.Buffer: + return r.ReadByte() + case *bytes.Reader: + return r.ReadByte() + case *bufio.Reader: + return r.ReadByte() + case *peeker: + return r.ReadByte() + case io.ByteReader: + return r.ReadByte() } var buf [1]byte _, err := io.ReadFull(r, buf[:1]) -- GitLab