Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reuse buffer #453

Merged
merged 2 commits into from
Dec 16, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 11 additions & 2 deletions encoding.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@ import (
"sync"
)

var bufPool = &sync.Pool{
New: func() interface{} {
return new(bytes.Buffer)
},
}

var varintPool = &sync.Pool{
New: func() interface{} {
return &[binary.MaxVarintLen64]byte{}
Expand Down Expand Up @@ -93,8 +99,11 @@ func encodeBytes(w io.Writer, bz []byte) error {

// encodeBytesSlice length-prefixes the byte slice and returns it.
func encodeBytesSlice(bz []byte) ([]byte, error) {
var buf bytes.Buffer
err := encodeBytes(&buf, bz)
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufPool.Put(buf)

err := encodeBytes(buf, bz)
return buf.Bytes(), err
}

Expand Down
8 changes: 5 additions & 3 deletions import.go
Original file line number Diff line number Diff line change
Expand Up @@ -119,9 +119,11 @@ func (i *Importer) Add(exportNode *ExportNode) error {
return err
}

var buf bytes.Buffer
err = node.writeBytes(&buf)
if err != nil {
buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufPool.Put(buf)

if err = node.writeBytes(buf); err != nil {
return err
}

Expand Down
10 changes: 8 additions & 2 deletions proof.go
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,10 @@ func (pin ProofInnerNode) stringIndented(indent string) string {

func (pin ProofInnerNode) Hash(childHash []byte) []byte {
hasher := sha256.New()
buf := new(bytes.Buffer)

buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufPool.Put(buf)

err := encodeVarint(buf, int64(pin.Height))
if err == nil {
Expand Down Expand Up @@ -145,7 +148,10 @@ func (pln ProofLeafNode) stringIndented(indent string) string {

func (pln ProofLeafNode) Hash() []byte {
hasher := sha256.New()
buf := new(bytes.Buffer)

buf := bufPool.Get().(*bytes.Buffer)
buf.Reset()
defer bufPool.Put(buf)

err := encodeVarint(buf, 0)
if err == nil {
Expand Down