For AI agents: A markdown version of this page is available at https://docs.datadoghq.com/security/code_security/static_analysis/static_analysis_rules/rust-code-quality/needless-collect.md. A documentation index is available at /llms.txt.

Unnecessary collection before len or is_empty check

This product is not supported for your selected Datadog site. ().

Metadata

ID: rust-code-quality/needless-collect

Language: Rust

Severity: Warning

Category: Performance

Description

Collecting an iterator into a Vec only to immediately call .len() or .is_empty() wastes a heap allocation. The intermediate collect can be replaced with a direct iterator method that produces the same result without allocating.

How to remediate?

// Before
let len = iter.collect::<Vec<_>>().len();
// After
let len = iter.count();

// Before
let empty = iter.collect::<Vec<_>>().is_empty();
// After
let empty = iter.next().is_none();

Non-Compliant Code Examples

fn needless_len(iter: impl Iterator<Item = i32>) -> usize {
    iter.collect::<Vec<_>>().len()
}

fn needless_is_empty(iter: impl Iterator<Item = i32>) -> bool {
    iter.collect::<Vec<_>>().is_empty()
}

fn needless_len_chained(iter: impl Iterator<Item = i32>) -> usize {
    iter.map(|x| x * 2).collect::<Vec<i32>>().len()
}

Compliant Code Examples

fn already_using_count(iter: impl Iterator<Item = i32>) -> usize {
    iter.count()
}

fn already_using_next_is_none(iter: impl Iterator<Item = i32>) -> bool {
    iter.next().is_none()
}

fn collect_used_multiple_times(iter: impl Iterator<Item = i32>) -> (usize, bool) {
    let v: Vec<_> = iter.collect();
    (v.len(), v.is_empty())
}

fn collect_returned(iter: impl Iterator<Item = i32>) -> Vec<i32> {
    iter.collect()
}
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security