From e7a0022232e5f9e947524c5b3216ed829fc92971 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Tom=C3=A1s?= <47506558+MegaRedHand@users.noreply.github.com> Date: Mon, 31 Jul 2023 19:24:23 -0300 Subject: [PATCH] perf: remove unneeded bitshift in validated addresses insertion (#1208) * Remove unneeded plus one * Clean up `validate_*`'s code * Replace `insert` with `push` in extend * Change approach The +1 in resize is used to avoid having to allocate in the case the next push falls outside capacity. Instead, we use a replace in the place of the insert. * Update changelog --------- Co-authored-by: Pedro Fontana --- CHANGELOG.md | 2 ++ vm/src/vm/vm_memory/memory.rs | 29 ++++++++++++++--------------- 2 files changed, 16 insertions(+), 15 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index dbf380cd34..ab33b72c76 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,8 @@ * fix: CLI errors bad formatting and handling +* perf: replace insertion with bit-setting in validated addresses [#1208](https://github.com/lambdaclass/cairo-vm/pull/1208) + * fix: return error when a parsed hint's PC is invalid [#1340](https://github.com/lambdaclass/cairo-vm/pull/1340) * chore(deps): bump _cairo-lang_ dependencies to v2.1.0-rc2 [#1345](https://github.com/lambdaclass/cairo-vm/pull/1345) diff --git a/vm/src/vm/vm_memory/memory.rs b/vm/src/vm/vm_memory/memory.rs index bfe3d3d8dc..098e2480fd 100644 --- a/vm/src/vm/vm_memory/memory.rs +++ b/vm/src/vm/vm_memory/memory.rs @@ -75,8 +75,7 @@ impl AddressSet { if offset >= self.0[segment].len() { self.0[segment].resize(offset + 1, false); } - - self.0[segment].insert(offset, true); + self.0[segment].replace(offset, true); } } } @@ -319,10 +318,8 @@ impl Memory { .and_then(|x| self.validation_rules.get(x)) { if !self.validated_addresses.contains(&addr) { - { - self.validated_addresses - .extend(rule.0(self, addr)?.as_slice()); - } + self.validated_addresses + .extend(rule.0(self, addr)?.as_slice()); } } Ok(()) @@ -331,15 +328,17 @@ impl Memory { ///Applies validation_rules to the current memory pub fn validate_existing_memory(&mut self) -> Result<(), MemoryError> { for (index, rule) in self.validation_rules.iter().enumerate() { - if let Some(rule) = rule { - if index < self.data.len() { - for offset in 0..self.data[index].len() { - let addr = Relocatable::from((index as isize, offset)); - if !self.validated_addresses.contains(&addr) { - self.validated_addresses - .extend(rule.0(self, addr)?.as_slice()); - } - } + if index >= self.data.len() { + continue; + } + let Some(rule) = rule else { + continue; + }; + for offset in 0..self.data[index].len() { + let addr = Relocatable::from((index as isize, offset)); + if !self.validated_addresses.contains(&addr) { + self.validated_addresses + .extend(rule.0(self, addr)?.as_slice()); } } }