Skip to content

Commit

Permalink
optimize byte reading
Browse files Browse the repository at this point in the history
When using cbor-gen, we _usually_ work with byte buffers/readers. Calling
`ReadByte` on a byte.Reader/byte.Buffer is much faster than calling `Read` and
copying into a slice.

    name            old time/op    new time/op    delta
    Marshaling-4       911ns ± 2%     904ns ± 5%     ~     (p=0.646 n=9+10)
    Unmarshaling-4    4.46µs ± 1%    3.94µs ± 2%  -11.55%  (p=0.000 n=10+8)
    LinkScan-4        4.65µs ± 2%    4.01µs ± 2%  -13.76%  (p=0.000 n=9+10)
    Deferred-4        3.68µs ± 3%    3.02µs ± 4%  -17.91%  (p=0.000 n=10+10)

    name            old alloc/op   new alloc/op   delta
    Marshaling-4        160B ± 0%      160B ± 0%     ~     (all equal)
    Unmarshaling-4    3.46kB ± 0%    3.46kB ± 0%     ~     (all equal)
    LinkScan-4          880B ± 0%      880B ± 0%     ~     (p=0.650 n=10+10)
    Deferred-4         96.0B ± 0%     96.0B ± 0%     ~     (all equal)

    name            old allocs/op  new allocs/op  delta
    Marshaling-4        10.0 ± 0%      10.0 ± 0%     ~     (all equal)
    Unmarshaling-4      43.0 ± 0%      43.0 ± 0%     ~     (all equal)
    LinkScan-4          25.0 ± 0%      25.0 ± 0%     ~     (all equal)
    Deferred-4          3.00 ± 0%      3.00 ± 0%     ~     (all equal)
  • Loading branch information
Stebalien committed Aug 7, 2020
1 parent 63aa96c commit 8649350
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -247,6 +247,16 @@ func CborReadHeader(br io.Reader) (byte, uint64, error) {
}

func readByteBuf(r io.Reader, scratch []byte) (byte, error) {
// Reading a single byte from these buffers is much faster than copying
// into a slice.
switch r := r.(type) {
case *bytes.Buffer:
return r.ReadByte()
case *bytes.Reader:
return r.ReadByte()
case *bufio.Reader:
return r.ReadByte()
}
n, err := r.Read(scratch[:1])
if err != nil {
return 0, err
Expand Down

0 comments on commit 8649350

Please sign in to comment.