---
title: Unnecessary collection before len or is_empty check
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Unnecessary collection before len or is_empty check
---

# Unnecessary collection before len or is_empty check

{% callout %}
# Important note for users on the following Datadog sites: app.ddog-gov.com, us2.ddog-gov.com

{% alert level="danger" %}
This product is not supported for your selected [Datadog site](https://docs.datadoghq.com/getting_started/site.md). ({% placeholder "user-datadog-site-name" /%}).
{% /alert %}

{% /callout %}

## Metadata{% #metadata %}

**ID:** `rust-code-quality/needless-collect`

**Language:** Rust

**Severity:** Warning

**Category:** Performance

## Description{% #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?{% #how-to-remediate %}

```rust
// 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{% #non-compliant-code-examples %}

```rust
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{% #compliant-code-examples %}

```rust
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()
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 