Skip to content

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

@nazar-pc

Description

@nazar-pc

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-iteratorsArea: IteratorsC-optimizationCategory: An issue highlighting optimization opportunities or PRs implementing suchI-slowIssue: Problems and improvements with respect to performance of generated code.T-libsRelevant to the library team, which will review and decide on the PR/issue.needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions