statesync: simplify Pool management code

* use slices.BinarySearchFunc with its boolean status
* use slices.Insert/slices.Delete, tnis can be a little less efficient, but it
  frees the memory faster and this code is more I/O (networking) bound to care
  about 1-3%

Signed-off-by: Roman Khimov <roman@nspcc.ru>
This commit is contained in:
Roman Khimov 2024-08-26 20:22:47 +03:00
parent 5431b31d84
commit a0553f740d

View file

@ -3,7 +3,6 @@ package statesync
import ( import (
"bytes" "bytes"
"slices" "slices"
"sort"
"sync" "sync"
"github.com/nspcc-dev/neo-go/pkg/util" "github.com/nspcc-dev/neo-go/pkg/util"
@ -94,11 +93,9 @@ func (mp *Pool) Update(remove map[util.Uint256][][]byte, add map[util.Uint256][]
for h, paths := range remove { for h, paths := range remove {
old := mp.hashes[h] old := mp.hashes[h]
for _, path := range paths { for _, path := range paths {
i := sort.Search(len(old), func(i int) bool { i, found := slices.BinarySearchFunc(old, path, bytes.Compare)
return bytes.Compare(old[i], path) >= 0 if found {
}) old = slices.Delete(old, i, i+1)
if i < len(old) && bytes.Equal(old[i], path) {
old = append(old[:i], old[i+1:]...)
} }
} }
if len(old) == 0 { if len(old) == 0 {
@ -116,18 +113,12 @@ func (mp *Pool) Update(remove map[util.Uint256][][]byte, add map[util.Uint256][]
func (mp *Pool) addPaths(nodeHash util.Uint256, paths [][]byte) { func (mp *Pool) addPaths(nodeHash util.Uint256, paths [][]byte) {
old := mp.hashes[nodeHash] old := mp.hashes[nodeHash]
for _, path := range paths { for _, path := range paths {
i := sort.Search(len(old), func(i int) bool { i, found := slices.BinarySearchFunc(old, path, bytes.Compare)
return bytes.Compare(old[i], path) >= 0 if found {
})
if i < len(old) && bytes.Equal(old[i], path) {
// then path is already added // then path is already added
continue continue
} }
old = append(old, path) old = slices.Insert(old, i, path)
if i != len(old)-1 {
copy(old[i+1:], old[i:])
old[i] = path
}
} }
mp.hashes[nodeHash] = old mp.hashes[nodeHash] = old
} }