rust-lang / rust-lang/rust-clippy
New lint suggestion: `iter_copied_too_late`
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 is the proposal of a Clippy perf lint to address the performance issue cited here: https://github.com/rust-lang/rust/issues/106539
It suggests moving .copied() in an iterator chain earlier if the resulting type would be a value type T anyways instead of &T.
This may result in confusing advice since it contradicts iter_overeager_cloned. However, to clone vs. copying things is genuinely different, so more experienced Rust users won't be too surprised.
Lint Name
iter_copied_too_late
Category
perf
Advantage
Especially with simple scalar types, this results in the usage of vector instructions when lowered to LLVM IR.
Drawbacks
Some false positives:
- if copying only removed a layer of indirection, from
&&Tto&Tinstead of&TtoT - type is too complex to vectorize (safest if it is a primitive or newtype of one)
- random other niche cases where this doesn't actually improve performance can happen also
Example
pub fn scalarized_max<T: Ord + Copy>(a: &[T]) -> Option<T> {
a.iter().max().copied()
}
This will typically drop to scalar code because LLVM can't immediately see that it can just dereference everything and reason about simple scalar types instaed. It could be written as:
pub fn vectorized_max<T: Ord + Copy>(a: &[T]) -> Option<T> {
a.iter().copied().max()
}
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 existing Clippy iterator performance lints and their tests; no specific files or entry points are named in the issue. Compare the proposed iter_copied_too_late behavior with iter_overeager_cloned, then add coverage for the iter().max().copied() example and verify that the suggested rewrite is emitted without inappropriate false positives.
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