0xMiden / 0xMiden/protocol

perf(protocol): eliminate temporary heap allocation and double serialization in AccountCode::get_size_hint

Offen
#3,629 1 Kommentar 0 Reaktionen 0 zugewiesene Personen Auf GitHub ansehen
Vorherrschende Sprache
Rust
Sterne
132
Forks
167
Ø Merge
1 T. 23 Std.
Gemergte PRs (30 T.)
110

Beschreibung

### Problem Description

In `crates/miden-protocol/src/account/code/mod.rs` (lines 301–315), `AccountCode::get_size_hint` is implemented by fully serializing the internal `MastForest` into a temporary `Vec` on the heap simply to measure its byte length:

```rust
fn get_size_hint(&self) -> usize {
// TODO: Replace with proper calculation.
let mut mast_forest_target = Vec::new();
self.mast.write_into(&mut mast_forest_target);

// Size of the serialized procedures length.
let u8_size = 0u8.get_size_hint();
let mut size = u8_size + mast_forest_target.len();

for procedure in self.procedures() {
size += procedure.get_size_hint();
}

size
}
```

When `AccountCode::to_bytes()` is called:
1. `Serializable::to_bytes(&self)` calls `self.get_size_hint()` to pre-allocate capacity in the destination vector.
2. `get_size_hint()` allocates a fresh heap buffer, serializes the entire `MastForest`, reads its length, and immediately drops the allocation.
3. `to_bytes` then calls `self.write_into(&mut target)`, serializing the exact same `MastForest` a second time.

This causes redundant heap allocations and duplicate serialization overhead on every `AccountCode` serialization.

### Proposed Solution
- Provide an accurate and non-allocating size estimation for `AccountCode::get_size_hint` based on the procedure count and component structure, avoiding the temporary heap allocation and double serialization.
- Add unit tests verifying `get_size_hint` accuracy against actual `to_bytes().len()`.

I would like to work on this issue.

Beitragsleitfaden

Beitragsleitfaden öffnen

Bewertung

Dieses Issue wurde noch nicht bewertet.

Neue Issues direkt in Ihr Postfach

Eine kurze Übersicht über anfängerfreundliche GitHub-Issues.