Skip to content
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

needless_collect triggers inside for loop, can be questionable #6909

Open
matthiaskrgr opened this issue Mar 15, 2021 · 2 comments
Open

needless_collect triggers inside for loop, can be questionable #6909

matthiaskrgr opened this issue Mar 15, 2021 · 2 comments
Labels
C-bug Category: Clippy is not doing the correct thing E-medium Call for participation: Medium difficulty level problem and requires some initial experience. I-false-positive Issue: The lint was triggered on code it shouldn't have L-nursery Lint: Currently in the nursery group

Comments

@matthiaskrgr
Copy link
Member

    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.

@matthiaskrgr matthiaskrgr added the L-perf Lint: Belongs in the perf lint group label Mar 15, 2021
@camsteffen
Copy link
Contributor

very similar to #6164

@camsteffen camsteffen added C-bug Category: Clippy is not doing the correct thing I-false-positive Issue: The lint was triggered on code it shouldn't have E-medium Call for participation: Medium difficulty level problem and requires some initial experience. labels Mar 29, 2021
@steveklabnik
Copy link
Member

Ran into this exact case today.

@J-ZhengLi J-ZhengLi added L-nursery Lint: Currently in the nursery group and removed L-perf Lint: Belongs in the perf lint group labels Jul 9, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
C-bug Category: Clippy is not doing the correct thing E-medium Call for participation: Medium difficulty level problem and requires some initial experience. I-false-positive Issue: The lint was triggered on code it shouldn't have L-nursery Lint: Currently in the nursery group
Projects
None yet
Development

No branches or pull requests

4 participants