Use std::unordered_set instead of std::vector in IsEvicted()

An unordered set can tell if an element is present in ~O(1) time (constant on
average, worst case linear to the size of the container), which speeds up and
simplifies the lookup in IsEvicted().

Co-authored-by: Vasil Dimov <vd@FreeBSD.org>
This commit is contained in:
Jon Atack 2021-02-28 15:53:07 +01:00
parent 41f84d5ecc
commit ca63b53ecd
No known key found for this signature in database
GPG key ID: 4F5721B3D0E3921D

View file

@ -10,6 +10,7 @@
#include <algorithm>
#include <functional>
#include <optional>
#include <unordered_set>
#include <vector>
BOOST_FIXTURE_TEST_SUITE(net_peer_eviction_tests, BasicTestingSetup)
@ -36,20 +37,20 @@ std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(const int n_c
}
// Returns true if any of the node ids in node_ids are selected for eviction.
bool IsEvicted(std::vector<NodeEvictionCandidate> candidates, const std::vector<NodeId>& node_ids, FastRandomContext& random_context)
bool IsEvicted(std::vector<NodeEvictionCandidate> candidates, const std::unordered_set<NodeId>& node_ids, FastRandomContext& random_context)
{
Shuffle(candidates.begin(), candidates.end(), random_context);
const std::optional<NodeId> evicted_node_id = SelectNodeToEvict(std::move(candidates));
if (!evicted_node_id) {
return false;
}
return std::find(node_ids.begin(), node_ids.end(), *evicted_node_id) != node_ids.end();
return node_ids.count(*evicted_node_id);
}
// Create number_of_nodes random nodes, apply setup function candidate_setup_fn,
// apply eviction logic and then return true if any of the node ids in node_ids
// are selected for eviction.
bool IsEvicted(const int number_of_nodes, std::function<void(NodeEvictionCandidate&)> candidate_setup_fn, const std::vector<NodeId>& node_ids, FastRandomContext& random_context)
bool IsEvicted(const int number_of_nodes, std::function<void(NodeEvictionCandidate&)> candidate_setup_fn, const std::unordered_set<NodeId>& node_ids, FastRandomContext& random_context)
{
std::vector<NodeEvictionCandidate> candidates = GetRandomNodeEvictionCandidates(number_of_nodes, random_context);
for (NodeEvictionCandidate& candidate : candidates) {