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/slow-vector-initialization.md. A documentation index is available at /llms.txt.

Vec initialized with new() then immediately resized

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

Metadata

ID: rust-code-quality/slow-vector-initialization

Language: Rust

Severity: Warning

Category: Performance

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

// 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

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

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);
}
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