Skip to content

Commit 56a365b

Browse files
authored
perf: optimize capacity reservation in HeaderMap's extend method (#788)
1 parent 691af72 commit 56a365b

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/header/map.rs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2127,6 +2127,19 @@ impl<T> Extend<(Option<HeaderName>, T)> for HeaderMap<T> {
21272127
fn extend<I: IntoIterator<Item = (Option<HeaderName>, T)>>(&mut self, iter: I) {
21282128
let mut iter = iter.into_iter();
21292129

2130+
// Reserve capacity similar to the (HeaderName, T) impl.
2131+
// Keys may be already present or show multiple times in the iterator.
2132+
// Reserve the entire hint lower bound if the map is empty.
2133+
// Otherwise reserve half the hint (rounded up), so the map
2134+
// will only resize twice in the worst case.
2135+
let reserve = if self.is_empty() {
2136+
iter.size_hint().0
2137+
} else {
2138+
(iter.size_hint().0 + 1) / 2
2139+
};
2140+
2141+
self.reserve(reserve);
2142+
21302143
// The structure of this is a bit weird, but it is mostly to make the
21312144
// borrow checker happy.
21322145
let (mut key, mut val) = match iter.next() {

0 commit comments

Comments
 (0)