Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
jovenlin0527 opened this issue May 9, 2023 · 2 comments · Fixed by #10777
Closed

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

jovenlin0527 opened this issue May 9, 2023 · 2 comments · Fixed by #10777
Labels
A-lint Area: New lints

Comments

@jovenlin0527
Copy link

jovenlin0527 commented May 9, 2023

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);
@jovenlin0527 jovenlin0527 added the A-lint Area: New lints label May 9, 2023
@jovenlin0527 jovenlin0527 changed the title Use extend(some_iter) over .extend(some_iter.collect())` Use extend(some_iter) over .extend(some_iter.collect()) May 9, 2023
@jovenlin0527 jovenlin0527 changed the title Use extend(some_iter) over .extend(some_iter.collect()) Use .extend(some_iter) over .extend(some_iter.collect()) May 9, 2023
@samueltardieu
Copy link
Contributor

This is not even specific to extend. It could be used everywhere a IntoIterator is expected.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-lint Area: New lints
Projects
None yet
2 participants