Skip to content

Commit e69cbac

Browse files
author
merge-script
committed
Merge bitcoin/bitcoin#22896: refactor: net: avoid duplicate map lookups to mapLocalHost
330d3aa 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 330d3aa jonatack: Code review ACK 330d3aa plus rebase to master + debug build Tree-SHA512: d13da6a927ff561eee8ac6b093bf3586dfe31d6c94173a5a6d8f3698e0ee224fb394d3635155d5141c165da59d2c2c37260122eb4f2e8bcda3e8a29b901d213e
2 parents 6401de0 + 330d3aa commit e69cbac

File tree

1 file changed

+10
-12
lines changed

1 file changed

+10
-12
lines changed

src/net.cpp

Lines changed: 10 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -192,8 +192,8 @@ CAddress GetLocalAddress(const CNetAddr *paddrPeer, ServiceFlags nLocalServices)
192192
static int GetnScore(const CService& addr)
193193
{
194194
LOCK(cs_mapLocalHost);
195-
if (mapLocalHost.count(addr) == 0) return 0;
196-
return mapLocalHost[addr].nScore;
195+
const auto it = mapLocalHost.find(addr);
196+
return (it != mapLocalHost.end()) ? it->second.nScore : 0;
197197
}
198198

199199
// Is our peer's addrLocal potentially useful as an external IP source?
@@ -245,10 +245,10 @@ bool AddLocal(const CService& addr, int nScore)
245245

246246
{
247247
LOCK(cs_mapLocalHost);
248-
bool fAlready = mapLocalHost.count(addr) > 0;
249-
LocalServiceInfo &info = mapLocalHost[addr];
250-
if (!fAlready || nScore >= info.nScore) {
251-
info.nScore = nScore + (fAlready ? 1 : 0);
248+
const auto [it, is_newly_added] = mapLocalHost.emplace(addr, LocalServiceInfo());
249+
LocalServiceInfo &info = it->second;
250+
if (is_newly_added || nScore >= info.nScore) {
251+
info.nScore = nScore + (is_newly_added ? 0 : 1);
252252
info.nPort = addr.GetPort();
253253
}
254254
}
@@ -290,12 +290,10 @@ bool IsReachable(const CNetAddr &addr)
290290
/** vote for a local address */
291291
bool SeenLocal(const CService& addr)
292292
{
293-
{
294-
LOCK(cs_mapLocalHost);
295-
if (mapLocalHost.count(addr) == 0)
296-
return false;
297-
mapLocalHost[addr].nScore++;
298-
}
293+
LOCK(cs_mapLocalHost);
294+
const auto it = mapLocalHost.find(addr);
295+
if (it == mapLocalHost.end()) return false;
296+
++it->second.nScore;
299297
return true;
300298
}
301299

0 commit comments

Comments
 (0)