Iterator collected only to be measured or iterated again
ID |
rust.performance.needless_collect |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Inefficient Api Usage |
Language |
Rust |
Description
collect allocates a whole collection that the next call immediately reduces again. Work on the iterator instead — count() for len(), next().is_none() for is_empty(), any() for contains() — and drop the collect when the result is only iterated once more.
Rationale
collect allocates a whole collection that the next call immediately reduces again. Work on the iterator instead — count() for len(), next().is_none() for is_empty(), any() for contains() — and drop the collect when the result is only iterated once more.
The following code illustrates the pattern detected by this rule:
fn count_long(names: &[String]) -> usize {
// FLAGGED: Iterator collected only to be measured or iterated again
names.iter().filter(|n| n.len() > 8).collect::<Vec<_>>().len()
}