From 88ea84cf12bb6a16e8307cb49252e95dfc77cc4d Mon Sep 17 00:00:00 2001 From: "Owain G. Ainsworth" Date: Wed, 23 Apr 2014 15:16:31 +0100 Subject: [PATCH] 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. --- addrmanager.go | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/addrmanager.go b/addrmanager.go index ba96a482d..cbdca7a26 100644 --- a/addrmanager.go +++ b/addrmanager.go @@ -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] }