Skip to content

Use .extend(some_iter) over .extend(some_iter.collect()) #10762

Closed
@jovenlin0527

Description

@jovenlin0527

What it does

Extend::extend takes an IntoIterator. Since every Iterator is also an IntoIterator, you can extend from an iterator; collect() an iterator before extend() from it leads to extra memory allocations and extra copying, and is probably a mistake.

Lint Name

extend_collect

Category

suspicious, perf

Advantage

Fewer memory allocations and fewer copying.

Drawbacks

Maybe collect() actually leads to a performance boost because of, say, better cache behavior, and is actually intentional.

Example

let mut v = vec![0i32];
v.extend((1..10).collect::<Vec<_>>());

Could be written as:

let mut v = vec![0i32];
v.extend(1..10);

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