From 747c1a4949e32f512a6170497885dbb601b00b07 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Tue, 12 Jul 2016 21:57:25 -0700 Subject: [PATCH] optimize getRandom. --- lib/bcoin/pool.js | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/lib/bcoin/pool.js b/lib/bcoin/pool.js index 7bf1b259..256a86e8 100644 --- a/lib/bcoin/pool.js +++ b/lib/bcoin/pool.js @@ -1524,7 +1524,7 @@ Pool.prototype.has = function has(type, hash, force, callback) { } else { // If we recently rejected this item. Ignore. if (self.rejects.test(hash, 'hex')) { - self.logger.debug('Peer sent a known reject: %s.', hash); + self.logger.debug('Peer sent a known reject: %s.', utils.revHex(hash)); return callback(null, true); } } @@ -1822,21 +1822,12 @@ Pool.prototype.getHost = function getHost() { */ Pool.prototype.getRandom = function getRandom(hosts, unique) { - var tried = {}; - var tries = 0; - var index, host; + var index = Math.random() * hosts.length | 0; + var last = -1; + var i, host; - for (;;) { - if (tries === hosts.length) - return; - - index = Math.random() * hosts.length | 0; - host = hosts[index]; - - if (!tried[index]) { - tried[index] = true; - tries++; - } + for (i = 0; i < hosts.length; i++) { + host = hosts[i]; if (this.isMisbehaving(host.host)) continue; @@ -1844,8 +1835,16 @@ Pool.prototype.getRandom = function getRandom(hosts, unique) { if (unique && this.getPeer(host.host)) continue; - return host; + if (i >= index) + return host; + + last = i; } + + if (last === -1) + return; + + return hosts[last]; }; /**