rust-lang / rust-lang/rust

Missed optimization with reserve and extend_from_slice

Open
#123,944 0 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-codegen A-LLVM C-optimization T-compiler
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code:

pub fn zzz(v: &mut Vec<u8>, s: &[u8]) {
    v.reserve(s.len());
    v.extend_from_slice(s);
}

I expected to see this happen: only one do_reserve_and_handle call.

Instead, this happened: extend_from_slice stills checks the capacity and calls reserve. It seems like LLVM assumes aren't able to bubble up out of multiple functions. I was able to get the optimization to work in https://github.com/rust-lang/rust/pull/119465 but it required putting assumes in every function along the reserve chain.

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

Start with the Rust code shown for Vec::reserve and extend_from_slice, then trace the reserve chain through do_reserve_and_handle. Compare the optimization approach in pull request 119465 and inspect whether the generated code still performs a capacity check and multiple reserve calls. Done means the example produces only one do_reserve_and_handle call.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Bug
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.