From 0e49e5c4855af73128e5a8c8f5a885a3af2c22a2 Mon Sep 17 00:00:00 2001 From: Brian Olson Date: Mon, 2 Sep 2024 12:15:53 -0400 Subject: [PATCH 1/2] use const [N]byte array in struct instead of heap allocated make([]byte) slice one less malloc()+GC per marshal --- io.go | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/io.go b/io.go index 4f3b309..c2f7af4 100644 --- a/io.go +++ b/io.go @@ -52,7 +52,7 @@ var ( type CborWriter struct { w io.Writer - hbuf []byte + hbuf [maxHeaderSize]byte sw io.StringWriter } @@ -63,8 +63,7 @@ func NewCborWriter(w io.Writer) *CborWriter { } cw := &CborWriter{ - w: w, - hbuf: make([]byte, maxHeaderSize), + w: w, } if sw, ok := w.(io.StringWriter); ok { @@ -88,11 +87,11 @@ func (cw *CborWriter) Write(p []byte) (n int, err error) { } func (cw *CborWriter) WriteMajorTypeHeader(t byte, l uint64) error { - return WriteMajorTypeHeaderBuf(cw.hbuf, cw.w, t, l) + return WriteMajorTypeHeaderBuf(cw.hbuf[:], cw.w, t, l) } func (cw *CborWriter) CborWriteHeader(t byte, l uint64) error { - return WriteMajorTypeHeaderBuf(cw.hbuf, cw.w, t, l) + return WriteMajorTypeHeaderBuf(cw.hbuf[:], cw.w, t, l) } func (cw *CborWriter) WriteString(s string) (int, error) { From 7af34898b1daa4be624350e1aa663d505d619f11 Mon Sep 17 00:00:00 2001 From: Brian Olson Date: Mon, 2 Sep 2024 14:56:16 -0400 Subject: [PATCH 2/2] save one alloc per NewCborReader() --- io.go | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/io.go b/io.go index c2f7af4..44beaf3 100644 --- a/io.go +++ b/io.go @@ -11,7 +11,7 @@ var ( type CborReader struct { r BytePeeker - hbuf []byte + hbuf [maxHeaderSize]byte } func NewCborReader(r io.Reader) *CborReader { @@ -20,8 +20,7 @@ func NewCborReader(r io.Reader) *CborReader { } return &CborReader{ - r: GetPeeker(r), - hbuf: make([]byte, maxHeaderSize), + r: GetPeeker(r), } } @@ -38,7 +37,7 @@ func (cr *CborReader) UnreadByte() error { } func (cr *CborReader) ReadHeader() (byte, uint64, error) { - return CborReadHeaderBuf(cr.r, cr.hbuf) + return CborReadHeaderBuf(cr.r, cr.hbuf[:]) } func (cr *CborReader) SetReader(r io.Reader) {