rust-lang / rust-lang/rust-clippy

needless_collect triggers inside for loop, can be questionable

Open
#6,909 2 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

C-bug E-medium I-false-positive L-nursery
Dominant language
Rust
Stars
13.5k
Forks
2.2k
Avg merge
2d 10h
Merged PRs (30d)
32

Description

    let v = vec![1, 2, 3, 4].into_iter().map(|x| /*very expensive closure */ x).collect::<Vec<_>>();
   
    for i in &[3, 4] {
        if v.contains(&i) {
            println!("got {}", i);
        }
    }

Right now, we are running the expensive closure only N (vec.len() times.
If we move it into into the for-loop, this could easily become N (vec.len() * M (for loop) times

fn main() {
    for i in &[3, 4] {
        if vec![1, 2, 3, 4].into_iter().map(|x| /* very expensive */ x).any(|x| x == *i) {
            println!("got {}", i);
        }
    }
}

it might be cheaper to just run the closure once up front for all the elements and "cache" the results in the vec.

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 locating the needless_collect lint and its existing tests, then compare them with the two Rust examples in this issue. Determine the intended behavior when the collected value is searched repeatedly inside a for loop, and add regression coverage that makes the accepted outcome explicit.

Written by the indexing model from the issue text.

Assessment

Tech stack
rust
Domain
tooling
Issue type
Feature
Difficulty
4/5
Estimated time
3-5 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
35/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.