avoid extra alloc on map

-   Before this change the code did:

  StorageRootTargets::new(
      prefix_sets.account_prefix_set.iter().map(|n|
  B256::from_slice(&nibbles.pack())),
      prefix_sets.storage_prefix_sets.clone(),
  ).len()

  StorageRootTargets::new(..) builds a brand-new
  B256Map<PrefixSet> by:

  - cloning every entry in storage_prefix_sets (each PrefixSet can
    hold dozens of nibble prefixes), and
  - allocating a fresh B256Map to hold them.

- We only needed the resulting length, so those clones/allocations
  were immediately thrown away.
This commit is contained in:
Yong Kang
2025-10-09 05:16:04 +00:00
parent e427485e16
commit 5647e22989
2 changed files with 21 additions and 5 deletions

View File

@@ -182,11 +182,10 @@ where
// Extend prefix sets with targets
let prefix_sets = Self::extend_prefix_sets_with_targets(&self.prefix_sets, &targets);
let storage_root_targets_len = StorageRootTargets::new(
prefix_sets.account_prefix_set.iter().map(|nibbles| B256::from_slice(&nibbles.pack())),
prefix_sets.storage_prefix_sets.clone(),
)
.len();
let storage_root_targets_len = StorageRootTargets::count(
&prefix_sets.account_prefix_set,
&prefix_sets.storage_prefix_sets,
);
trace!(
target: "trie::parallel_proof",

View File

@@ -24,6 +24,23 @@ impl StorageRootTargets {
.collect(),
)
}
/// Returns the total number of unique storage root targets without allocating new maps.
pub fn count(
account_prefix_set: &PrefixSet,
storage_prefix_sets: &B256Map<PrefixSet>,
) -> usize {
let mut count = storage_prefix_sets.len();
for nibbles in account_prefix_set.iter() {
let hashed_address = B256::from_slice(&nibbles.pack());
if !storage_prefix_sets.contains_key(&hashed_address) {
count += 1;
}
}
count
}
}
impl IntoIterator for StorageRootTargets {