Skip to content

Commit

Permalink
perf: remove reallocations in compute hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
0xdeafbeef committed Oct 12, 2024
1 parent 70068b0 commit 0de3320
Showing 1 changed file with 13 additions and 5 deletions.
18 changes: 13 additions & 5 deletions src/cell/cell_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,9 +89,6 @@ impl<'a> CellParts<'a> {

let references = self.references.as_ref();

// `hashes_len` is guaranteed to be in range 1..4
let mut hashes_len = level + 1;

let (cell_type, computed_level_mask) = if unlikely(descriptor.is_exotic()) {
let Some(&first_byte) = self.data.first() else {
return Err(Error::InvalidCell);
Expand All @@ -114,7 +111,6 @@ impl<'a> CellParts<'a> {
return Err(Error::InvalidCell);
}

hashes_len = 1;
(CellType::PrunedBranch, level_mask)
}
// 8 bits type, hash, depth
Expand Down Expand Up @@ -157,7 +153,19 @@ impl<'a> CellParts<'a> {
let level_offset = cell_type.is_merkle() as u8;
let is_pruned = cell_type.is_pruned_branch();

let mut hashes = Vec::<(HashBytes, u16)>::with_capacity(hashes_len);
// this calculation mimics the underlying loop to avoid reallocations
let mut hashes = {
let mut hashes_len = 0;
for lvl in 0..4 {
// Skip non-zero levels for pruned branches and insignificant hashes for other cells
if lvl != 0 && (is_pruned || !level_mask.contains(lvl)) {
continue;
}
hashes_len += 1;
}
Vec::<(HashBytes, u16)>::with_capacity(hashes_len)
};

for level in 0..4 {
// Skip non-zero levels for pruned branches and insignificant hashes for other cells
if level != 0 && (is_pruned || !level_mask.contains(level)) {
Expand Down

0 comments on commit 0de3320

Please sign in to comment.