Addrman: only shuffle as much as we need.

If we switch the knuth shuffle to the version that swaps the element
with an element between it and the end of the array, then once we have
gotten to the amount of elements we need they won't change later in the
algorithm. Terminating here means that we only do 23% of the length of
the array worth of random swaps at most.
This commit is contained in:
Owain G. Ainsworth 2014-04-23 15:16:31 +01:00
parent ec8d0e582c
commit 88ea84cf12

View file

@ -720,17 +720,20 @@ func (a *AddrManager) AddressCache() []*btcwire.NetAddress {
allAddr[i] = v.na
i++
}
// Fisher-Yates shuffle the array
for i := range allAddr {
j := rand.Intn(i + 1)
allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
}
numAddresses := len(allAddr) * getAddrPercent / 100
if numAddresses > getAddrMax {
numAddresses = getAddrMax
}
// Fisher-Yates shuffle the array. We only need to do the first
// `numAddresses' since we are throwing the rest.
for i := 0; i < numAddresses; i++ {
// pick a number between current index and the end
j := rand.Intn(len(allAddr)-i) + i
allAddr[i], allAddr[j] = allAddr[j], allAddr[i]
}
// slice off the limit we are willing to share.
return allAddr[:numAddresses]
}