From e064487ca28c12ba774c2f43a3c7acbdb1a278c9 Mon Sep 17 00:00:00 2001 From: brunoerg Date: Thu, 23 Mar 2023 15:45:56 -0300 Subject: [PATCH] addrman, refactor: improve stochastic test in `AddSingle` This commit changes this algo to be O(1) instead of O(n) by using `<<`. --- src/addrman.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/src/addrman.cpp b/src/addrman.cpp index 212baab9d45..5d532bedf9c 100644 --- a/src/addrman.cpp +++ b/src/addrman.cpp @@ -585,11 +585,10 @@ bool AddrManImpl::AddSingle(const CAddress& addr, const CNetAddr& source, std::c return false; // stochastic test: previous nRefCount == N: 2^N times harder to increase it - int nFactor = 1; - for (int n = 0; n < pinfo->nRefCount; n++) - nFactor *= 2; - if (nFactor > 1 && (insecure_rand.randrange(nFactor) != 0)) - return false; + if (pinfo->nRefCount > 0) { + const int nFactor{1 << pinfo->nRefCount}; + if (insecure_rand.randrange(nFactor) != 0) return false; + } } else { pinfo = Create(addr, source, &nId); pinfo->nTime = std::max(NodeSeconds{0s}, pinfo->nTime - time_penalty);