perf(trie): pre-allocate prefix sets (#6466)

This commit is contained in:
Roman Krasiuk
2024-02-07 18:12:57 +01:00
committed by GitHub
parent 2bcdec94ab
commit e085f4524f
2 changed files with 11 additions and 10 deletions

View File

@ -48,6 +48,11 @@ where
}
impl PrefixSetMut {
/// Create [PrefixSetMut] with pre-allocated capacity.
pub fn with_capacity(capacity: usize) -> Self {
Self { keys: Vec::with_capacity(capacity), ..Default::default() }
}
/// Returns `true` if any of the keys in the set has the given prefix or
/// if the given prefix is a prefix of any key in the set.
pub fn contains(&mut self, prefix: &[u8]) -> bool {

View File

@ -145,29 +145,25 @@ impl HashedPostState {
/// The prefix sets contain the hashed account and storage keys that have been changed in the
/// post state.
pub fn construct_prefix_sets(&self) -> (PrefixSet, HashMap<B256, PrefixSet>) {
// Initialize prefix sets.
let mut account_prefix_set = PrefixSetMut::default();
let mut storage_prefix_set: HashMap<B256, PrefixSetMut> = HashMap::default();
// Populate account prefix set.
let mut account_prefix_set = PrefixSetMut::with_capacity(self.accounts.len());
for hashed_address in self.accounts.keys() {
account_prefix_set.insert(Nibbles::unpack(hashed_address));
}
// Populate storage prefix sets.
let mut storage_prefix_sets = HashMap::with_capacity(self.storages.len());
for (hashed_address, hashed_storage) in self.storages.iter() {
account_prefix_set.insert(Nibbles::unpack(hashed_address));
let storage_prefix_set_entry = storage_prefix_set.entry(*hashed_address).or_default();
let mut prefix_set = PrefixSetMut::with_capacity(hashed_storage.storage.len());
for hashed_slot in hashed_storage.storage.keys() {
storage_prefix_set_entry.insert(Nibbles::unpack(hashed_slot));
prefix_set.insert(Nibbles::unpack(hashed_slot));
}
storage_prefix_sets.insert(*hashed_address, prefix_set.freeze());
}
(
account_prefix_set.freeze(),
storage_prefix_set.into_iter().map(|(k, v)| (k, v.freeze())).collect(),
)
(account_prefix_set.freeze(), storage_prefix_sets)
}
/// Calculate the state root for this [HashedPostState].