Skip to content

Commit

Permalink
Conditionally allocate WaitGroup memory (#2901)
Browse files Browse the repository at this point in the history
  • Loading branch information
StephenButtolph authored Apr 2, 2024
1 parent e7b14e4 commit 5be62de
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 3 deletions.
11 changes: 8 additions & 3 deletions x/merkledb/view.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,7 +316,7 @@ func (v *view) hashChangedNode(n *node) ids.ID {
lastKeyByte byte

// We use [wg] to wait until all descendants of [n] have been updated.
wg sync.WaitGroup
wg waitGroup
)

if bytesForKey > 0 {
Expand Down Expand Up @@ -360,11 +360,16 @@ func (v *view) hashChangedNode(n *node) ids.ID {
// Try updating the child and its descendants in a goroutine.
if ok := v.db.hashNodesSema.TryAcquire(1); ok {
wg.Add(1)
go func(childEntry *child) {

// Passing variables explicitly through the function call rather
// than implicitly passing them through the scope of the function
// definition allows the passed variables to be allocated on the
// stack.
go func(wg *sync.WaitGroup, childEntry *child) {
childEntry.id = v.hashChangedNode(childNodeChange.after)
v.db.hashNodesSema.Release(1)
wg.Done()
}(childEntry)
}(wg.wg, childEntry)
} else {
// We're at the goroutine limit; do the work in this goroutine.
childEntry.id = v.hashChangedNode(childNodeChange.after)
Expand Down
25 changes: 25 additions & 0 deletions x/merkledb/wait_group.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package merkledb

import "sync"

// waitGroup is a small wrapper of a sync.WaitGroup that avoids performing a
// memory allocation when Add is never called.
type waitGroup struct {
wg *sync.WaitGroup
}

func (wg *waitGroup) Add(delta int) {
if wg.wg == nil {
wg.wg = new(sync.WaitGroup)
}
wg.wg.Add(delta)
}

func (wg *waitGroup) Wait() {
if wg.wg != nil {
wg.wg.Wait()
}
}
29 changes: 29 additions & 0 deletions x/merkledb/wait_group_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// Copyright (C) 2019-2024, Ava Labs, Inc. All rights reserved.
// See the file LICENSE for licensing terms.

package merkledb

import "testing"

func Benchmark_WaitGroup_Wait(b *testing.B) {
for i := 0; i < b.N; i++ {
var wg waitGroup
wg.Wait()
}
}

func Benchmark_WaitGroup_Add(b *testing.B) {
for i := 0; i < b.N; i++ {
var wg waitGroup
wg.Add(1)
}
}

func Benchmark_WaitGroup_AddDoneWait(b *testing.B) {
for i := 0; i < b.N; i++ {
var wg waitGroup
wg.Add(1)
wg.wg.Done()
wg.Wait()
}
}

0 comments on commit 5be62de

Please sign in to comment.