When a program knows the expected number of items, reserving capacity avoids repeated growth work.

Program

Play the program to choose extra capacity and watch the vector keep length and capacity separate.

extra
preallocate_vector.rs
Replay: real traced execution (multi-file project)
fn main() {
    let extra = 2;
    let mut items = Vec::with_capacity(3 + extra);
    items.push("parse");
    items.push("trace");
    items.push("replay");
    println!("len={} capacity={}", items.len(), items.capacity());
}
fn main() {
    let extra = 0;
    let mut items = Vec::with_capacity(3 + extra);
    items.push("parse");
    items.push("trace");
    items.push("replay");
    println!("len={} capacity={}", items.len(), items.capacity());
}
fn main() {
    let extra = 4;
    let mut items = Vec::with_capacity(3 + extra);
    items.push("parse");
    items.push("trace");
    items.push("replay");
    println!("len={} capacity={}", items.len(), items.capacity());
}
  1. extra ← 2, items ← []

    1fn main() {2    let extr→ 2a = 2; //@extra=2, 0, 43    let mut item→ []s = Vec::with_capacity(3 + extr2a);4    items.push("parse");5    items.push("trace");6    items.push("replay");7    println!("len={} capacity={}", items.len(), items.capacity());8}
    outputlen=3 capacity=5
  1. extra ← 0, items ← []

    1fn main() {2    let extr→ 0a = 0;3    let mut item→ []s = Vec::with_capacity(3 + extr0a);4    items.push("parse");5    items.push("trace");6    items.push("replay");7    println!("len={} capacity={}", items.len(), items.capacity());8}
    outputlen=3 capacity=3
  1. extra ← 4, items ← []

    1fn main() {2    let extr→ 4a = 4;3    let mut item→ []s = Vec::with_capacity(3 + extr4a);4    items.push("parse");5    items.push("trace");6    items.push("replay");7    println!("len={} capacity={}", items.len(), items.capacity());8}
    outputlen=3 capacity=7
capacity `Vec::with_capacity` reserves storage without changing the vector length.
growth Choosing enough capacity up front avoids extra reallocations while pushing known items.
length `len` counts initialized elements; `capacity` counts reserved slots.