rust-lang / rust-lang/rust

Vec-growing logic emitted for Vecs which never grow

Open
#118,563 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-optimization I-heavy T-compiler T-libs
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

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. 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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.