From a687464ea1f241f69611ea9603d70bc2943208fc Mon Sep 17 00:00:00 2001 From: Michael Sproul Date: Wed, 3 Aug 2022 13:08:03 +1000 Subject: [PATCH 1/2] Pre-allocate vectors in SSZ decoding --- consensus/ssz/src/decode/try_from_iter.rs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/consensus/ssz/src/decode/try_from_iter.rs b/consensus/ssz/src/decode/try_from_iter.rs index 22db02d4fc8..dc33b2538be 100644 --- a/consensus/ssz/src/decode/try_from_iter.rs +++ b/consensus/ssz/src/decode/try_from_iter.rs @@ -29,11 +29,18 @@ pub trait TryFromIter: Sized { impl TryFromIter for Vec { type Error = Infallible; - fn try_from_iter(iter: I) -> Result + fn try_from_iter(values: I) -> Result where I: IntoIterator, { - Ok(Self::from_iter(iter)) + // Pre-allocate the max size of the Vec. We expect to receive vastly more valid + // messages to decode, and the max length has already been vetted by + // `decode_list_of_variable_length_items`. + let iter = values.into_iter(); + let (_, opt_max_len) = iter.size_hint(); + let mut vec = Vec::with_capacity(opt_max_len.unwrap_or(0)); + vec.extend(iter); + Ok(vec) } } From ce5ecf9ca67013b1bb9245de54d4ebcf55b85161 Mon Sep 17 00:00:00 2001 From: Michael Sproul Date: Wed, 14 Sep 2022 11:23:50 +1000 Subject: [PATCH 2/2] Clarify comment (thanks Sean) --- consensus/ssz/src/decode/try_from_iter.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/consensus/ssz/src/decode/try_from_iter.rs b/consensus/ssz/src/decode/try_from_iter.rs index dc33b2538be..1ff89a107f4 100644 --- a/consensus/ssz/src/decode/try_from_iter.rs +++ b/consensus/ssz/src/decode/try_from_iter.rs @@ -33,9 +33,9 @@ impl TryFromIter for Vec { where I: IntoIterator, { - // Pre-allocate the max size of the Vec. We expect to receive vastly more valid - // messages to decode, and the max length has already been vetted by - // `decode_list_of_variable_length_items`. + // Pre-allocate the expected size of the Vec, which is parsed from the SSZ input bytes as + // `num_items`. This length has already been checked to be less than or equal to the type's + // maximum length in `decode_list_of_variable_length_items`. let iter = values.into_iter(); let (_, opt_max_len) = iter.size_hint(); let mut vec = Vec::with_capacity(opt_max_len.unwrap_or(0));