Skip to content

Commit aa080f4

Browse files
committed
Be much less clever about things
This one only helps lower>0, but by doing so means it's always strictly less than 100% overhead, same as the normal doubling algorithm. And thus doesn't need to do the try_reserve dance or a post-extend cleanup.
1 parent d545902 commit aa080f4

File tree

1 file changed

+6
-25
lines changed

1 file changed

+6
-25
lines changed

src/liballoc/vec.rs

Lines changed: 6 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1861,36 +1861,17 @@ impl<T, I> SpecExtend<T, I> for Vec<T>
18611861
if let Some(x) = iterator.next() { x }
18621862
else { return Vec::new() };
18631863
let (lower, upper) = iterator.size_hint();
1864-
let upper = upper.unwrap_or(lower);
1865-
let mut vector =
1866-
if lower >= upper / 2 {
1867-
// This branch covers three main cases:
1868-
// - There was no upper bound, so we just use the lower.
1869-
// - The hint turned out to be exact, so we use it.
1870-
// - Picking the upper won't waste more that the doubling
1871-
// strategy might anyway, so go directly there.
1872-
Vec::with_capacity(upper.saturating_add(1))
1873-
} else {
1874-
// Try to start near the geometric mean of the range. That's
1875-
// never all that high -- even 0B..1GB will only allocate 32kB --
1876-
// but it's much more useful than the lower bound, especially
1877-
// for iterator adapters like filter that have lower == 0.
1878-
let mut v = Vec::new();
1879-
let mag_diff = lower.leading_zeros() - upper.leading_zeros();
1880-
let guess = upper >> (mag_diff / 2);
1881-
match v.try_reserve(guess.saturating_add(1)) {
1882-
Ok(_) => v,
1883-
Err(_) => Vec::with_capacity(lower.saturating_add(1)),
1884-
}
1885-
};
1864+
let guess = if let Some(upper) = upper {
1865+
lower.saturating_mul(2).min(upper)
1866+
} else {
1867+
lower
1868+
};
1869+
let mut vector = Vec::with_capacity(guess.saturating_add(1));
18861870
unsafe {
18871871
ptr::write(vector.get_unchecked_mut(0), element);
18881872
vector.set_len(1);
18891873
}
18901874
<Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
1891-
if vector.len() < vector.capacity() / 2 {
1892-
vector.shrink_to_fit();
1893-
}
18941875
vector
18951876
}
18961877

0 commit comments

Comments
 (0)