Vec-growing logic emitted for Vecs which never grow
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 119k
- Forks
- 16.1k
- PR merge metrics
- PR metrics pending
Description
Consider these two examples:
pub fn foo(sizes: &[u64]) -> u64 {
let mut top = Vec::with_capacity(1);
for &size in sizes {
/*if top.capacity() <= top.len() {
unsafe { std::hint::unreachable_unchecked() }
}*/
top.push(size);
top.pop();
}
top.iter().sum()
}
pub fn bar(sizes: &[u64]) -> u64 {
const TOP_ELEMENTS: usize = 3;
let mut top = Vec::with_capacity(TOP_ELEMENTS + 1);
for &size in sizes {
/*if top.capacity() <= top.len() {
unsafe { std::hint::unreachable_unchecked() }
}*/
let i = 0; //top.partition_point(|&cur| cur > size);
top.insert(i, size);
top.truncate(TOP_ELEMENTS);
}
top.iter().sum()
}
Godbolt: https://rust.godbolt.org/z/PhrMr7dYr
Neither are ever going to grow their Vec from the initial size. Yet, RawVec::reserve_for_push and friends are emitted when compiling.
Uncommenting the unreachable_unchecked hints allows the optimizer to clean everything up. Might be asking a lot of the compiler but it would be great if it could figure that out by itself.
Tested with Rust 1.74 and with 1.76.0-nightly (87e1447aa 2023-11-30).
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Reproduce foo and bar with Rust 1.74 or the cited nightly, then compare their generated assembly using the linked Godbolt example. Investigate the emitted RawVec::reserve_for_push and related growth paths; done means the unnecessary Vec-growth logic is eliminated without the unreachable_unchecked hints.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- compilers, performance
- Issue type
- Bug
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100