optimize getRandom.

This commit is contained in:
Christopher Jeffrey 2016-07-12 21:57:25 -07:00
parent a6dc5a08c8
commit 747c1a4949
No known key found for this signature in database
GPG Key ID: 8962AB9DE6666BBD

View File

@ -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];
};
/**