rust-lang / rust-lang/rust

`Vec::into_iter().flatten().collect::<Vec<_>>()` doesn't reuse allocation

Open
#146,270 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

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

Description

Here is a simple example:

pub fn flatten_array(ys: Vec<[u32; 288]>) -> Vec<u32> {
    ys
        .into_iter()
        .flatten()
        .collect()
}

Godbolt

It is obvious that the size and alignment will be exactly the same after conversion, yet right now Rust generates a bunch of code instead of efficiently reusing allocation like it does with similar vec.into_iter().map().collect() cases.

I'm sure there is a reason for this that might be non-trivial, but I don't think this is completely unreasonable either.

Similar issue happens with .flat_map(), which I tried to use originally.

UPD: Just discovered Vec::into_flattened(), which does exactly what I need with a simple .flatten(), but still doesn't cover .flat_map() and thus not as generic.

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 by reproducing the Rust example in the linked Godbolt reproduction and compare its generated code with the noted Vec::into_flattened() behavior. Read the relevant iterator flatten, flat_map, and collect paths; done means the applicable cases reuse the existing allocation without regressing other collection behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
compilers, performance
Issue type
Feature
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.