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

Remove memory alloc from encodeDBNode #2893

Merged
merged 2 commits into from
Apr 2, 2024
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
15 changes: 10 additions & 5 deletions x/merkledb/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,6 @@ import (
"math/bits"
"slices"

"golang.org/x/exp/maps"

"github.com/ava-labs/avalanchego/ids"
"github.com/ava-labs/avalanchego/utils/maybe"
)
Expand Down Expand Up @@ -139,9 +137,16 @@ func encodeDBNode(n *dbNode) []byte {
buf := bytes.NewBuffer(make([]byte, 0, encodedDBNodeSize(n)))
encodeMaybeByteSlice(buf, n.value)
encodeUint(buf, uint64(len(n.children)))
// Note we insert children in order of increasing index
// for determinism.
keys := maps.Keys(n.children)

// By allocating BranchFactorLargest rather than len(n.children), this slice
// is allocated on the stack rather than the heap. BranchFactorLargest is
// at least len(n.children) which avoids memory allocations.
keys := make([]byte, 0, BranchFactorLargest)
for k := range n.children {
keys = append(keys, k)
}

// Ensure that the order of entries is correct.
slices.Sort(keys)
for _, index := range keys {
entry := n.children[index]
Expand Down