---
title: Vec initialized with new() then immediately resized
description: Datadog, the leading service for cloud-scale monitoring.
breadcrumbs: >-
  Docs > Datadog Security > Code Security > Static Code Analysis (SAST) > SAST
  Rules > Vec initialized with new() then immediately resized
---

# Vec initialized with new() then immediately resized

{% 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/slow-vector-initialization`

**Language:** Rust

**Severity:** Warning

**Category:** Performance

## Description{% #description %}

Calling `Vec::new()` or `Vec::with_capacity(n)` and then immediately calling `.resize()` on the result is slower than using the `vec!` macro, which allocates and fills in a single step.

## Example{% #example %}

```rust
// Before — two-step initialization
let mut v = Vec::new();
v.resize(n, 0);

// After — single step
let v = vec![0; n];
```

## Non-Compliant Code Examples{% #non-compliant-code-examples %}

```rust
fn slow_new_resize(n: usize) -> Vec<i32> {
    let mut v = Vec::new();
    v.resize(n, 0);
    v
}

fn slow_with_capacity_resize(n: usize) -> Vec<i32> {
    let mut v = Vec::with_capacity(n);
    v.resize(n, 0);
    v
}

fn slow_with_capacity_with_type(n: usize) -> Vec<i32> {
  let mut v = Vec::<i32>::with_capacity(n);
  v.resize(n, 0);
  v
}
```

## Compliant Code Examples{% #compliant-code-examples %}

```rust
fn reserve_not_resize(n: usize) -> Vec<i32> {
    let mut v = Vec::new();
    v.reserve(n);
    v
}

fn non_adjacent(n: usize) -> Vec<i32> {
    let mut v = Vec::new();
    println!("creating vec");
    v.resize(n, 0);
    v
}

fn different_vars(n: usize) {
    let mut v = Vec::new();
    let mut w = Vec::new();
    v.resize(n, 0);
}
```
  Seamless integrations. Try Datadog Code SecurityDatadog Code Security 
{% icon name="icon-external-link" /%}
 