rust-lang / rust-lang/rust-clippy
Suggest `collect`ing a range instead of pushing `i` onto vector in a `for` loop
Nobody has claimed this yet.
- Dominant language
- Rust
- Stars
- 13.5k
- Forks
- 2.2k
- Avg merge
- 2d 10h
- Merged PRs (30d)
- 32
Description
What it does
This lint finds for loops (with incrementing i) used only to populate vectors with the value of i on each execution of the loop. The lint suggest the better way of populating a vector, that is using collect on a range. Please look in the code example to see a demonstration. I also invite you to run the benchmarks yourself to see how much faster the collect method is; I have written some test and published them in this gist.
I have encountered this issue in the wild. In someone's code a vector was being filled in a for loop with consecutive numbers. To my great surprie clippy did not find this worrisome. That's why I am submitting this issue.
Lint Name
needless_for_loop
Category
perf
Advantage
- Massive performance increase in comparison to a for loop.
- More compact, idiomatic code.
Drawbacks
Populating a vector with a for loop guarantees that the vector is mutable. Populating a vector with range collection does not make such a guarantee. However if the lint is implemented correctly then it should not care about mutability nor should it change mutability if --fix is on.
Example
let mut v: Vec<i32> = Vec::new();
for i in 0..50000 {
v.push(i);
}
Could be written as:
let mut v = (0..50000).collect::<Vec<i32>>();
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 from the needless_for_loop lint description and its Rust example. Review the benchmark gist to compare the loop and range-collect approaches. Done means the lint recognizes this vector-population pattern, suggests range collection, and does not incorrectly alter mutability when --fix is used.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- devtools
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 43/100