Skip to content

Commit 047a2e0

Browse files
committed
p2p/discover: optimize findnodeByID
1 parent d3679c2 commit 047a2e0

File tree

1 file changed

+16
-11
lines changed

1 file changed

+16
-11
lines changed

p2p/discover/table.go

Lines changed: 16 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -245,28 +245,33 @@ func (tab *Table) refresh() <-chan struct{} {
245245
// preferLive is true and the table contains any verified nodes, the result will not
246246
// contain unverified nodes. However, if there are no verified nodes at all, the result
247247
// will contain unverified nodes.
248-
func (tab *Table) findnodeByID(target enode.ID, nresults int, preferLive bool) *nodesByDistance {
248+
func (tab *Table) findnodeByID(target enode.ID, nresults int, preferLive bool) (nodes nodesByDistance) {
249+
nodes.target = target
249250
tab.mutex.Lock()
250251
defer tab.mutex.Unlock()
251252

252253
// Scan all buckets. There might be a better way to do this, but there aren't that many
253254
// buckets, so this solution should be fine. The worst-case complexity of this loop
254255
// is O(tab.len() * nresults).
255-
nodes := &nodesByDistance{target: target}
256-
liveNodes := &nodesByDistance{target: target}
257-
for _, b := range &tab.buckets {
258-
for _, n := range b.entries {
259-
nodes.push(n.Node, nresults)
260-
if preferLive && n.isValidatedLive {
261-
liveNodes.push(n.Node, nresults)
256+
if preferLive {
257+
for _, b := range &tab.buckets {
258+
for _, n := range b.entries {
259+
if n.isValidatedLive {
260+
nodes.push(n.Node, nresults)
261+
}
262262
}
263263
}
264+
if len(nodes.entries) > 0 {
265+
return
266+
}
264267
}
265268

266-
if preferLive && len(liveNodes.entries) > 0 {
267-
return liveNodes
269+
for _, b := range &tab.buckets {
270+
for _, n := range b.entries {
271+
nodes.push(n.Node, nresults)
272+
}
268273
}
269-
return nodes
274+
return
270275
}
271276

272277
// appendBucketNodes adds nodes at the given distance to the result slice.

0 commit comments

Comments
 (0)