From c2150df23e4fb01e968fe90304731eb1d994bcff Mon Sep 17 00:00:00 2001 From: gabrielbosio Date: Fri, 23 Jan 2026 16:58:39 -0300 Subject: [PATCH] perf: pre-allocate collections during program deserialization - Pre-allocate Vec in MaybeRelocatableVisitor::visit_seq using size_hint - Pre-allocate HashMap in ReferenceIdsVisitor::visit_map using size_hint - Remove redundant .to_string() call when value is already a String This reduces allocation overhead during JSON program deserialization. Benchmark shows ~5% improvement in initialize time. --- CHANGELOG.md | 2 ++ vm/src/serde/deserialize_program.rs | 8 +++++--- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index cf9634b41c..0671c94b2a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ #### Upcoming Changes +* perf: Pre-allocate collections during program deserialization [#2300](https://github.com/lambdaclass/cairo-vm/pull/2300) + * feat: Add public `ORDERED_BUILTIN_LIST` constant [#2298](https://github.com/lambdaclass/cairo-vm/pull/2298) * chore(breaking): Remove bincode crate [#2294](https://github.com/lambdaclass/cairo-vm/pull/2294) diff --git a/vm/src/serde/deserialize_program.rs b/vm/src/serde/deserialize_program.rs index 2c483da77d..a45d24fb01 100644 --- a/vm/src/serde/deserialize_program.rs +++ b/vm/src/serde/deserialize_program.rs @@ -341,11 +341,12 @@ impl<'de> de::Visitor<'de> for MaybeRelocatableVisitor { where A: SeqAccess<'de>, { - let mut data: Vec = vec![]; + let mut data: Vec = + Vec::with_capacity(seq.size_hint().unwrap_or_default()); while let Some(value) = seq.next_element::()? { // Add padding if necessary - let value = deserialize_utils::maybe_add_padding(value.to_string()); + let value = deserialize_utils::maybe_add_padding(value); data.push(MaybeRelocatable::Int( Felt252::from_hex(&value).map_err(de::Error::custom)?, )); @@ -367,7 +368,8 @@ impl<'de> de::Visitor<'de> for ReferenceIdsVisitor { where A: MapAccess<'de>, { - let mut data: HashMap = HashMap::new(); + let mut data: HashMap = + HashMap::with_capacity(map.size_hint().unwrap_or_default()); while let Some((key, value)) = map.next_entry::()? { data.insert(key, value);