Skip to content

Commit

Permalink
chore(lib/trie): refactor trie.go and fix additional memory problems (
Browse files Browse the repository at this point in the history
#2255)

- Linear refactor of functions for easier reading
- If not modified, nodes of the previous trie generation are returned, meaning newer copied nodes will be left for garbage collection
- Comments revised, reduced or added depending on the case
- Split functions into smaller functions
  • Loading branch information
qdm12 authored Feb 17, 2022
1 parent 8db8b2a commit 9ac6642
Show file tree
Hide file tree
Showing 4 changed files with 923 additions and 621 deletions.
5 changes: 5 additions & 0 deletions internal/trie/node/branch.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@ import (

var _ Node = (*Branch)(nil)

const (
// ChildrenCapacity is the maximum number of children in a branch node.
ChildrenCapacity = 16
)

// Branch is a branch in the trie.
type Branch struct {
// Partial key bytes in nibbles (0 to f in hexadecimal)
Expand Down
6 changes: 3 additions & 3 deletions internal/trie/node/branch_encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -161,7 +161,7 @@ var parallelEncodingRateLimit = make(chan struct{}, parallelLimit)
func encodeChildrenOpportunisticParallel(children [16]Node, buffer io.Writer) (err error) {
// Buffered channels since children might be encoded in this
// goroutine or another one.
resultsCh := make(chan encodingAsyncResult, len(children))
resultsCh := make(chan encodingAsyncResult, ChildrenCapacity)

for i, child := range children {
if isNodeNil(child) || child.Type() == LeafType {
Expand All @@ -183,7 +183,7 @@ func encodeChildrenOpportunisticParallel(children [16]Node, buffer io.Writer) (e
}

currentIndex := 0
resultBuffers := make([]*bytes.Buffer, len(children))
resultBuffers := make([]*bytes.Buffer, ChildrenCapacity)
for range children {
result := <-resultsCh
if result.err != nil && err == nil { // only set the first error we get
Expand All @@ -193,7 +193,7 @@ func encodeChildrenOpportunisticParallel(children [16]Node, buffer io.Writer) (e
resultBuffers[result.index] = result.buffer

// write as many completed buffers to the result buffer.
for currentIndex < len(children) &&
for currentIndex < ChildrenCapacity &&
resultBuffers[currentIndex] != nil {
bufferSlice := resultBuffers[currentIndex].Bytes()
if err == nil && len(bufferSlice) > 0 {
Expand Down
Loading

0 comments on commit 9ac6642

Please sign in to comment.