From c449d82abafeb93a468c423d60caa594a9061787 Mon Sep 17 00:00:00 2001 From: Ariaj Sarkar Date: Mon, 27 Oct 2025 23:05:16 +0530 Subject: [PATCH] feat: optimize capacity reservation in HeaderMap's extend method --- src/header/map.rs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/header/map.rs b/src/header/map.rs index e3f3d342..0fb567cc 100644 --- a/src/header/map.rs +++ b/src/header/map.rs @@ -2126,6 +2126,19 @@ impl Extend<(Option, T)> for HeaderMap { fn extend, T)>>(&mut self, iter: I) { let mut iter = iter.into_iter(); + // Reserve capacity similar to the (HeaderName, T) impl. + // Keys may be already present or show multiple times in the iterator. + // Reserve the entire hint lower bound if the map is empty. + // Otherwise reserve half the hint (rounded up), so the map + // will only resize twice in the worst case. + let reserve = if self.is_empty() { + iter.size_hint().0 + } else { + (iter.size_hint().0 + 1) / 2 + }; + + self.reserve(reserve); + // The structure of this is a bit weird, but it is mostly to make the // borrow checker happy. let (mut key, mut val) = match iter.next() {