Merge bitcoin/bitcoin#22896: refactor: net: avoid duplicate map lookups to mapLocalHost

330d3aa1a2c740dfa31bed3a6ed6b5f88e5426ad refactor: net: avoid duplicate map lookups to `mapLocalHost` (Sebastian Falbesoner)

Pull request description:

  This simple refactoring PR aims to avoid duplicate lookups to `mapLocalHost`: instead of calling `count()` (to first find out whether a key is in the map) and then `operator[]` (to get the value to the passed key, or default-construct one if not found), use either
  * `find()` and dereference the returned iterator (for simple lookups), see https://www.cplusplus.com/reference/map/map/find/
  * `emplace()` and use the returned <iterator, inserted> pair (for lookups where a new element should be inserted if the key isn't found), see https://www.cplusplus.com/reference/map/map/emplace/

ACKs for top commit:
  naumenkogs:
    ACK 330d3aa1a2c740dfa31bed3a6ed6b5f88e5426ad
  jonatack:
    Code review ACK 330d3aa1a2c740dfa31bed3a6ed6b5f88e5426ad plus rebase to master + debug build

Tree-SHA512: d13da6a927ff561eee8ac6b093bf3586dfe31d6c94173a5a6d8f3698e0ee224fb394d3635155d5141c165da59d2c2c37260122eb4f2e8bcda3e8a29b901d213e
This commit is contained in:
merge-script 2021-09-17 14:25:10 +02:00 committed by pasta
parent 082bfe79a0
commit cf403b7ca7

View File

@ -183,8 +183,8 @@ CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
static int GetnScore(const CService& addr) static int GetnScore(const CService& addr)
{ {
LOCK(cs_mapLocalHost); LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0) return 0; const auto it = mapLocalHost.find(addr);
return mapLocalHost[addr].nScore; return (it != mapLocalHost.end()) ? it->second.nScore : 0;
} }
// Is our peer's addrLocal potentially useful as an external IP source? // Is our peer's addrLocal potentially useful as an external IP source?
@ -238,10 +238,10 @@ bool AddLocal(const CService& addr, int nScore)
{ {
LOCK(cs_mapLocalHost); LOCK(cs_mapLocalHost);
bool fAlready = mapLocalHost.count(addr) > 0; const auto [it, is_newly_added] = mapLocalHost.emplace(addr, LocalServiceInfo());
LocalServiceInfo &info = mapLocalHost[addr]; LocalServiceInfo &info = it->second;
if (!fAlready || nScore >= info.nScore) { if (is_newly_added || nScore >= info.nScore) {
info.nScore = nScore + (fAlready ? 1 : 0); info.nScore = nScore + (is_newly_added ? 0 : 1);
info.nPort = addr.GetPort(); info.nPort = addr.GetPort();
} }
} }
@ -282,13 +282,11 @@ bool IsReachable(const CNetAddr &addr)
/** vote for a local address */ /** vote for a local address */
bool SeenLocal(const CService& addr) bool SeenLocal(const CService& addr)
{
{ {
LOCK(cs_mapLocalHost); LOCK(cs_mapLocalHost);
if (mapLocalHost.count(addr) == 0) const auto it = mapLocalHost.find(addr);
return false; if (it == mapLocalHost.end()) return false;
mapLocalHost[addr].nScore++; ++it->second.nScore;
}
return true; return true;
} }