Skip to content

Commit ca63b53

Browse files
jonatackvasild
andcommitted
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 <[email protected]>
1 parent 41f84d5 commit ca63b53

File tree

1 file changed

+4
-3
lines changed

1 file changed

+4
-3
lines changed

src/test/net_peer_eviction_tests.cpp

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
#include <algorithm>
1111
#include <functional>
1212
#include <optional>
13+
#include <unordered_set>
1314
#include <vector>
1415

1516
BOOST_FIXTURE_TEST_SUITE(net_peer_eviction_tests, BasicTestingSetup)
@@ -36,20 +37,20 @@ std::vector<NodeEvictionCandidate> GetRandomNodeEvictionCandidates(const int n_c
3637
}
3738

3839
// Returns true if any of the node ids in node_ids are selected for eviction.
39-
bool IsEvicted(std::vector<NodeEvictionCandidate> candidates, const std::vector<NodeId>& node_ids, FastRandomContext& random_context)
40+
bool IsEvicted(std::vector<NodeEvictionCandidate> candidates, const std::unordered_set<NodeId>& node_ids, FastRandomContext& random_context)
4041
{
4142
Shuffle(candidates.begin(), candidates.end(), random_context);
4243
const std::optional<NodeId> evicted_node_id = SelectNodeToEvict(std::move(candidates));
4344
if (!evicted_node_id) {
4445
return false;
4546
}
46-
return std::find(node_ids.begin(), node_ids.end(), *evicted_node_id) != node_ids.end();
47+
return node_ids.count(*evicted_node_id);
4748
}
4849

4950
// Create number_of_nodes random nodes, apply setup function candidate_setup_fn,
5051
// apply eviction logic and then return true if any of the node ids in node_ids
5152
// are selected for eviction.
52-
bool IsEvicted(const int number_of_nodes, std::function<void(NodeEvictionCandidate&)> candidate_setup_fn, const std::vector<NodeId>& node_ids, FastRandomContext& random_context)
53+
bool IsEvicted(const int number_of_nodes, std::function<void(NodeEvictionCandidate&)> candidate_setup_fn, const std::unordered_set<NodeId>& node_ids, FastRandomContext& random_context)
5354
{
5455
std::vector<NodeEvictionCandidate> candidates = GetRandomNodeEvictionCandidates(number_of_nodes, random_context);
5556
for (NodeEvictionCandidate& candidate : candidates) {

0 commit comments

Comments
 (0)