Skip to content

Commit

Permalink
fix: reduce memory healed by deferred objects
Browse files Browse the repository at this point in the history
`bytes.Buffer` will always overallocate (for performance) and we don't
have a great way of predicting the correct size. So, instead, copy once
when we're done.
  • Loading branch information
Stebalien committed Apr 19, 2024
1 parent c5f90eb commit 7b3233f
Showing 1 changed file with 3 additions and 5 deletions.
8 changes: 3 additions & 5 deletions deferred.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,10 +24,7 @@ func (d *Deferred) MarshalCBOR(w io.Writer) error {
}

func (d *Deferred) UnmarshalCBOR(br io.Reader) (err error) {
// Reuse any existing buffers.
reusedBuf := d.Raw[:0]
d.Raw = nil
buf := bytes.NewBuffer(reusedBuf)
buf := bytes.NewBuffer(nil)

// Allocate some scratch space.
scratch := make([]byte, maxHeaderSize)
Expand Down Expand Up @@ -90,6 +87,7 @@ func (d *Deferred) UnmarshalCBOR(br io.Reader) (err error) {
return fmt.Errorf("unhandled deferred cbor type: %d", maj)
}
}
d.Raw = buf.Bytes()
d.Raw = d.Raw[:0]
d.Raw = append(d.Raw, buf.Bytes()...)
return nil
}

0 comments on commit 7b3233f

Please sign in to comment.