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
}