Skip to content

Commit b87581f

Browse files
authored
p2p/enode: optimize DistCmp (#32888)
This speeds up DistCmp by 75% through using 64-bit operations instead of byte-wise XOR.
1 parent 5c6ba6b commit b87581f

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

p2p/enode/node.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -359,9 +359,10 @@ func ParseID(in string) (ID, error) {
359359
// Returns -1 if a is closer to target, 1 if b is closer to target
360360
// and 0 if they are equal.
361361
func DistCmp(target, a, b ID) int {
362-
for i := range target {
363-
da := a[i] ^ target[i]
364-
db := b[i] ^ target[i]
362+
for i := 0; i < len(target); i += 8 {
363+
tn := binary.BigEndian.Uint64(target[i : i+8])
364+
da := tn ^ binary.BigEndian.Uint64(a[i:i+8])
365+
db := tn ^ binary.BigEndian.Uint64(b[i:i+8])
365366
if da > db {
366367
return 1
367368
} else if da < db {

p2p/enode/node_test.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -368,6 +368,16 @@ func TestID_distcmpEqual(t *testing.T) {
368368
}
369369
}
370370

371+
func BenchmarkDistCmp(b *testing.B) {
372+
base := ID{0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15}
373+
aID := ID{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0}
374+
bID := ID{15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 1}
375+
b.ResetTimer()
376+
for i := 0; i < b.N; i++ {
377+
_ = DistCmp(base, aID, bID)
378+
}
379+
}
380+
371381
func TestID_logdist(t *testing.T) {
372382
logdistBig := func(a, b ID) int {
373383
abig, bbig := new(big.Int).SetBytes(a[:]), new(big.Int).SetBytes(b[:])

0 commit comments

Comments
 (0)