rust-lang / rust-lang/rust

`String.extend(repeat_n(...))` could optimize better

Open
#145,434 3 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

A-iterators A-str C-optimization T-libs
Dominant language
Rust
Stars
119k
Forks
16.1k
PR merge metrics
PR metrics pending

Description

I tried this code (godbolt):

pub fn f(s: &mut String, n: usize) {
    s.extend(std::iter::repeat_n(' ', n))
}

I expected to see this happen: optimizes to memset or similar

Instead, this happened: scalar loop with unoptimized capacity checks/reserve calls

The equivalent version using Vec optimizes as expected:

pub fn f(s: &mut String, n: usize) {
    unsafe { s.as_mut_vec() }.extend(std::iter::repeat_n(b' ', n));
}
Meta

rustc --version --verbose:

rustc 1.91.0-nightly (3672a55b7 2025-08-13)
binary: rustc
commit-hash: 3672a55b7cfd0a12e7097197b6242872473ffaa7
commit-date: 2025-08-13
host: x86_64-unknown-linux-gnu
release: 1.91.0-nightly
LLVM version: 21.1.0

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 linked Godbolt reproducer and inspect the implementations of String::extend and repeat_n while comparing their generated assembly with the Vec version. Determine why capacity checks and reserve calls remain in the String path; done means the reported case generates memset-like code without regressing relevant behavior.

Written by the indexing model from the issue text.

Assessment

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

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.