rust-lang / rust-lang/rust-clippy
needless_collect triggers inside for loop, can be questionable
Nobody has claimed this yet.
- 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
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- 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