diff --git a/crates/trie/common/src/prefix_set.rs b/crates/trie/common/src/prefix_set.rs index 35c4bc67839..f9cf5ac9655 100644 --- a/crates/trie/common/src/prefix_set.rs +++ b/crates/trie/common/src/prefix_set.rs @@ -205,6 +205,12 @@ impl PrefixSet { return true } + // Early bounds check to help compiler eliminate redundant checks in the while loop + // If index is out of bounds, reset to 0 to avoid unnecessary backward scanning + if self.index >= self.keys.len() { + self.index = 0; + } + while self.index > 0 && &self.keys[self.index] > prefix { self.index -= 1; }