diff --git a/consensus/ssz/src/decode/try_from_iter.rs b/consensus/ssz/src/decode/try_from_iter.rs index 22db02d4f..1ff89a107 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 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)); + vec.extend(iter); + Ok(vec) } }