trie: Optimize keys function (#11457)

* trie: Optimize `keys` function

Instead of iterating the entire state and collecting all keys that match the given prefix, we can
directly use the optimized prefix iterator.

* Add a test
This commit is contained in:
Bastian Köcher
2022-05-18 21:20:47 +02:00
committed by GitHub
parent 9dd9a98eff
commit 516a8fa433
2 changed files with 25 additions and 18 deletions
@@ -453,22 +453,9 @@ where
/// Returns all keys that start with the given `prefix`.
pub fn keys(&self, prefix: &[u8]) -> Vec<StorageKey> {
let collect_all = || -> sp_std::result::Result<_, Box<TrieError<H::Out>>> {
let trie = TrieDB::<H>::new(self, &self.root)?;
let mut v = Vec::new();
for x in trie.iter()? {
let (key, _) = x?;
if key.starts_with(prefix) {
v.push(key.to_vec());
}
}
Ok(v)
};
collect_all()
.map_err(|e| debug!(target: "trie", "Error extracting trie keys: {}", e))
.unwrap_or_default()
let mut keys = Vec::new();
self.for_keys_with_prefix(prefix, |k| keys.push(k.to_vec()));
keys
}
/// Return the storage root after applying the given `delta`.