From 122b740e2d4c17fd0fc93cf331eedd56e78fe22b Mon Sep 17 00:00:00 2001 From: Alexander Block Date: Tue, 7 Apr 2020 06:55:09 +0200 Subject: [PATCH] Optimize deletion of vNodes entries Iterate through the vectors with iterators and use them for .erase(). This avoids an expensive lookup when erasing. --- src/net.cpp | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/src/net.cpp b/src/net.cpp index fc09517470..ba514b3ba7 100644 --- a/src/net.cpp +++ b/src/net.cpp @@ -1239,9 +1239,9 @@ void CConnman::ThreadSocketHandler() { LOCK(cs_vNodes); // Disconnect unused nodes - std::vector vNodesCopy = vNodes; - for (CNode* pnode : vNodesCopy) + for (auto it = vNodes.begin(); it != vNodes.end(); ) { + CNode* pnode = *it; if (pnode->fDisconnect) { if (fLogIPs) { @@ -1253,7 +1253,7 @@ void CConnman::ThreadSocketHandler() } // remove from vNodes - vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); + it = vNodes.erase(it); // release outbound grant (if any) pnode->grantOutbound.Release(); @@ -1265,17 +1265,20 @@ void CConnman::ThreadSocketHandler() // hold in disconnected pool until all refs are released pnode->Release(); vNodesDisconnected.push_back(pnode); + } else { + ++it; } } } { // Delete disconnected nodes std::list vNodesDisconnectedCopy = vNodesDisconnected; - for (CNode* pnode : vNodesDisconnectedCopy) + for (auto it = vNodesDisconnected.begin(); it != vNodesDisconnected.end(); ) { + CNode* pnode = *it; // wait until threads are done using it + bool fDelete = false; if (pnode->GetRefCount() <= 0) { - bool fDelete = false; { TRY_LOCK(pnode->cs_inventory, lockInv); if (lockInv) { @@ -1286,10 +1289,13 @@ void CConnman::ThreadSocketHandler() } } if (fDelete) { - vNodesDisconnected.remove(pnode); + it = vNodesDisconnected.erase(it); DeleteNode(pnode); } } + if (!fDelete) { + ++it; + } } } size_t vNodesSize;