Vec filled in a loop without reserving capacity

ID

rust.performance.slow_vector_initialization

Severity

info

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Inefficient Api Usage

Language

Rust

Description

Reports an empty Vec created with Vec::new() or vec![] and then filled by a for loop that pushes one element per pass, with no capacity reserved beforehand.

Rationale

An empty Vec starts with no buffer, so it reallocates and moves its contents each time the capacity is exhausted - a run of allocations and copies for a length that is already known from the collection being iterated. The loop also spreads one operation over four lines, which hides that the result is simply the input mapped element by element.

The following code illustrates the pattern detected by this rule:

pub fn widths(names: &[String]) -> Vec<usize> {
    // FLAGGED: Vec filled in a loop without reserving capacity
    let mut widths = Vec::new();
    for name in names {
        widths.push(name.len());
    }
    widths
}

Remediation

Build it in one expression - names.iter().map(|n| n.len()).collect() - which reserves from the iterator’s size hint. Where the loop has to stay, create the vector with Vec::with_capacity(source.len()), or call reserve before the loop.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved