Skip to content

Commit

Permalink
Assign instead of append to keys slice (#2932)
Browse files Browse the repository at this point in the history
Co-authored-by: Stephen Buttolph <[email protected]>
  • Loading branch information
Dan Laine and StephenButtolph authored Apr 10, 2024
1 parent 5c070f8 commit f461ec4
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
10 changes: 6 additions & 4 deletions x/merkledb/codec.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,12 +90,14 @@ func encodeDBNode(n *dbNode) []byte {
return w.b
}

// By allocating BranchFactorLargest rather than len(n.children), this slice
// By allocating BranchFactorLargest rather than [numChildren], 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)
// at least [numChildren] which avoids memory allocations.
keys := make([]byte, numChildren, BranchFactorLargest)
i := 0
for k := range n.children {
keys = append(keys, k)
keys[i] = k
i++
}

// Ensure that the order of entries is correct.
Expand Down
10 changes: 6 additions & 4 deletions x/merkledb/hashing.go
Original file line number Diff line number Diff line change
Expand Up @@ -51,13 +51,15 @@ func (*sha256Hasher) HashNode(n *node) ids.ID {

// Avoid allocating keys entirely if the node doesn't have any children.
if numChildren != 0 {
// By allocating BranchFactorLargest rather than len(n.children), this
// By allocating BranchFactorLargest rather than [numChildren], this
// slice is allocated on the stack rather than the heap.
// BranchFactorLargest is at least len(n.children) which avoids memory
// BranchFactorLargest is at least [numChildren] which avoids memory
// allocations.
keys := make([]byte, 0, BranchFactorLargest)
keys := make([]byte, numChildren, BranchFactorLargest)
i := 0
for k := range n.children {
keys = append(keys, k)
keys[i] = k
i++
}

// Ensure that the order of entries is correct.
Expand Down

0 comments on commit f461ec4

Please sign in to comment.