Optimize deletion of vNodes entries

Iterate through the vectors with iterators and use them for .erase().
This avoids an expensive lookup when erasing.
This commit is contained in:
Alexander Block 2020-04-07 06:55:09 +02:00
parent 481339355d
commit 122b740e2d

View File

@ -1239,9 +1239,9 @@ void CConnman::ThreadSocketHandler()
{ {
LOCK(cs_vNodes); LOCK(cs_vNodes);
// Disconnect unused nodes // Disconnect unused nodes
std::vector<CNode*> vNodesCopy = vNodes; for (auto it = vNodes.begin(); it != vNodes.end(); )
for (CNode* pnode : vNodesCopy)
{ {
CNode* pnode = *it;
if (pnode->fDisconnect) if (pnode->fDisconnect)
{ {
if (fLogIPs) { if (fLogIPs) {
@ -1253,7 +1253,7 @@ void CConnman::ThreadSocketHandler()
} }
// remove from vNodes // remove from vNodes
vNodes.erase(remove(vNodes.begin(), vNodes.end(), pnode), vNodes.end()); it = vNodes.erase(it);
// release outbound grant (if any) // release outbound grant (if any)
pnode->grantOutbound.Release(); pnode->grantOutbound.Release();
@ -1265,17 +1265,20 @@ void CConnman::ThreadSocketHandler()
// hold in disconnected pool until all refs are released // hold in disconnected pool until all refs are released
pnode->Release(); pnode->Release();
vNodesDisconnected.push_back(pnode); vNodesDisconnected.push_back(pnode);
} else {
++it;
} }
} }
} }
{ {
// Delete disconnected nodes // Delete disconnected nodes
std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected; std::list<CNode*> vNodesDisconnectedCopy = vNodesDisconnected;
for (CNode* pnode : vNodesDisconnectedCopy) for (auto it = vNodesDisconnected.begin(); it != vNodesDisconnected.end(); )
{ {
CNode* pnode = *it;
// wait until threads are done using it // wait until threads are done using it
bool fDelete = false;
if (pnode->GetRefCount() <= 0) { if (pnode->GetRefCount() <= 0) {
bool fDelete = false;
{ {
TRY_LOCK(pnode->cs_inventory, lockInv); TRY_LOCK(pnode->cs_inventory, lockInv);
if (lockInv) { if (lockInv) {
@ -1286,10 +1289,13 @@ void CConnman::ThreadSocketHandler()
} }
} }
if (fDelete) { if (fDelete) {
vNodesDisconnected.remove(pnode); it = vNodesDisconnected.erase(it);
DeleteNode(pnode); DeleteNode(pnode);
} }
} }
if (!fDelete) {
++it;
}
} }
} }
size_t vNodesSize; size_t vNodesSize;