Skip to content

Suggestion of collect_push_then_iter for iterators #14946

Open
@profetia

Description

@profetia

What it does

When an iterator is collected into vector, which is then push()-ed into right after and then turned backed into iterator to do other things, it should be rewrite into a chain() instead.

Advantage

  • Make the code more readable
  • Remove redudant allocations for better performance

Drawbacks

  • Not sure if the compiler is smart enough to optimize it out

Example

fn collect_push_then_iter(iter: impl Iterator<Item = i32>) -> Vec<i32> {
    let mut v = iter.collect::<Vec<_>>();
    v.push(1);
    v = v.into_iter().map(|x| x + 1).collect();
    v
}

Could be written as:

fn collect_push_then_iter(iter: impl Iterator<Item = i32>) -> Vec<i32> {
    iter.chain(std::iter::once(1)).map(|x| x + 1).collect()
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-lintArea: New lints

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions