Skip to content

Commit

Permalink
Remove memory alloc from encodeDBNode (#2893)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenButtolph authored Apr 2, 2024
1 parent 4163dce commit 9a0c852
Show file tree
Hide file tree
Showing 2 changed files with 389 additions and 136 deletions.
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
Loading

0 comments on commit 9a0c852

Please sign in to comment.