trie: implement bytepool

This commit is contained in:
Martin Holst Swende 2024-11-11 22:54:26 +01:00
parent 22f86a7668
commit 5880b2bdeb
No known key found for this signature in database
GPG Key ID: 683B438C05A5DDF0
2 changed files with 42 additions and 3 deletions

39
trie/bytepool.go Normal file
View File

@ -0,0 +1,39 @@
package trie
type bytepool struct {
c chan []byte
w int
h int
}
func newByteslicepool(sliceCap, nitems int) *bytepool {
b := &bytepool{
c: make(chan []byte, nitems),
w: sliceCap,
}
return b
}
func (bp *bytepool) Get() []byte {
select {
case b := <-bp.c:
return b
default:
return make([]byte, 0, bp.w)
}
}
func (bp *bytepool) Put(b []byte) {
// Ignore too small slices
if cap(b) < bp.w {
return
}
// Don't retain too large slices either
if cap(b) > 3*bp.w {
return
}
select {
case bp.c <- b:
default:
}
}

View File

@ -27,7 +27,7 @@ import (
var (
stPool = sync.Pool{New: func() any { return new(stNode) }}
bPool = sync.Pool{New: func() any { return make([]byte, 0, 32) }}
bPool = newByteslicepool(32, 100)
_ = types.TrieHasher((*StackTrie)(nil))
)
@ -398,7 +398,7 @@ func (t *StackTrie) hash(st *stNode, path []byte) {
// Skip committing the non-root node if the size is smaller than 32 bytes
// as tiny nodes are always embedded in their parent except root node.
if len(blob) < 32 && len(path) > 0 {
val := bPool.Get().([]byte)
val := bPool.Get()
val = val[:len(blob)]
copy(val, blob)
st.val = val
@ -406,7 +406,7 @@ func (t *StackTrie) hash(st *stNode, path []byte) {
}
// Write the hash to the 'val'. We allocate a new val here to not mutate
// input values.
val := bPool.Get().([]byte)
val := bPool.Get()
val = val[:32]
t.h.hashDataTo(blob, val)
st.val = val