From 974a56dffdb6edfbba44c31673754cf7f3d62014 Mon Sep 17 00:00:00 2001 From: RunasSudo Date: Sat, 20 Aug 2022 23:39:15 +1000 Subject: [PATCH] Improve performance of Candidate in HashMap by simplifying equality check --- src/constraints.rs | 1 + src/election.rs | 12 ++++++++++-- 2 files changed, 11 insertions(+), 2 deletions(-) diff --git a/src/constraints.rs b/src/constraints.rs index 21649c3..d77f58e 100644 --- a/src/constraints.rs +++ b/src/constraints.rs @@ -775,6 +775,7 @@ pub fn init_repeat_count(election: &mut Election) { let mut new_candidates = Vec::new(); for candidate in &election.candidates { let mut new_candidate = candidate.clone(); + new_candidate.index += election.candidates.len(); // Ensure unique index new_candidate.is_dummy = true; new_candidates.push(new_candidate); } diff --git a/src/election.rs b/src/election.rs index b4998f6..bb7c81e 100644 --- a/src/election.rs +++ b/src/election.rs @@ -100,7 +100,7 @@ impl Election { } /// A candidate in an [Election] -#[derive(Clone, Eq, PartialEq)] +#[derive(Clone, Eq)] #[cfg_attr(not(target_arch = "wasm32"), derive(Archive, Deserialize, Serialize))] pub struct Candidate { /// Index of the candidate @@ -111,13 +111,21 @@ pub struct Candidate { pub is_dummy: bool, } +impl PartialEq for Candidate { + // Custom implementation of eq for HashMap purposes, to improve performance + // + // SAFETY: Results in undefined behaviour if multiple Candidates are allowed to have the same index + fn eq(&self, other: &Candidate) -> bool { + return self.index == other.index; + } +} + impl Hash for Candidate { fn hash(&self, hasher: &mut H) { // Custom implementation of hash for use with NoHashHasher, to improve performance hasher.write_usize(self.index); } } - impl nohash_hasher::IsEnabled for Candidate {} /// The current state of counting an [Election]