trie: implement bytepool
This commit is contained in:
parent
22f86a7668
commit
5880b2bdeb
|
@ -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:
|
||||||
|
}
|
||||||
|
}
|
|
@ -27,7 +27,7 @@ import (
|
||||||
|
|
||||||
var (
|
var (
|
||||||
stPool = sync.Pool{New: func() any { return new(stNode) }}
|
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))
|
_ = 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
|
// 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.
|
// as tiny nodes are always embedded in their parent except root node.
|
||||||
if len(blob) < 32 && len(path) > 0 {
|
if len(blob) < 32 && len(path) > 0 {
|
||||||
val := bPool.Get().([]byte)
|
val := bPool.Get()
|
||||||
val = val[:len(blob)]
|
val = val[:len(blob)]
|
||||||
copy(val, blob)
|
copy(val, blob)
|
||||||
st.val = val
|
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
|
// Write the hash to the 'val'. We allocate a new val here to not mutate
|
||||||
// input values.
|
// input values.
|
||||||
val := bPool.Get().([]byte)
|
val := bPool.Get()
|
||||||
val = val[:32]
|
val = val[:32]
|
||||||
t.h.hashDataTo(blob, val)
|
t.h.hashDataTo(blob, val)
|
||||||
st.val = val
|
st.val = val
|
||||||
|
|
Loading…
Reference in New Issue