Skip to content

Try to guess a smarter initial capacity in Vec::from_iter #53086

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 13 additions & 11 deletions src/liballoc/vec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1857,18 +1857,20 @@ impl<T, I> SpecExtend<T, I> for Vec<T>
// empty, but the loop in extend_desugared() is not going to see the
// vector being full in the few subsequent loop iterations.
// So we get better branch prediction.
let mut vector = match iterator.next() {
None => return Vec::new(),
Some(element) => {
let (lower, _) = iterator.size_hint();
let mut vector = Vec::with_capacity(lower.saturating_add(1));
unsafe {
ptr::write(vector.get_unchecked_mut(0), element);
vector.set_len(1);
}
vector
}
let element =
if let Some(x) = iterator.next() { x }
else { return Vec::new() };
let (lower, upper) = iterator.size_hint();
let guess = if let Some(upper) = upper {
lower.saturating_mul(2).min(upper)
} else {
lower
};
let mut vector = Vec::with_capacity(guess.saturating_add(1));
unsafe {
ptr::write(vector.get_unchecked_mut(0), element);
vector.set_len(1);
}
<Vec<T> as SpecExtend<T, I>>::spec_extend(&mut vector, iterator);
vector
}
Expand Down