Preallocate Vec Capacity Before Pushing

Push into a Vec that grows on demand or into one preallocated with with_capacity, watching capacity() so reallocation points are observed rather than guessed.

RustData Integrity

Code

rustsnippet
23 lines
fn main() {
    // 未预分配:push 越过容量时重新分配
    let mut grown: Vec<u32> = Vec::new();
    for n in 1..=8 {
        if grown.len() == grown.capacity() {
            println!("grow needed at len {} (cap {})", grown.len(), grown.capacity());
        }
        grown.push(n);
    }
    println!("grown: len {} cap {}", grown.len(), grown.capacity());

    // 已知元素个数:with_capacity 一次性预分配(preallocate)容量
    let mut planned: Vec<u32> = Vec::with_capacity(8);
    let cap_before = planned.capacity();
    for n in 1..=8 {
        planned.push(n);
    }
    println!(
        "planned: len {} cap unchanged {}",
        planned.len(),
        planned.capacity() == cap_before
    );
}

What the code does

Preallocate Vec Capacity Before Pushing comes down to the function main.

Iteration happens inside for n in 1..=8 — everything outside it runs once.

Applying it

The demo output is labeled (grow needed at len, grown: len, planned: len), so every printed line maps back to its originating operation.

Statements that matter

let mut planned: Vec<u32> = Vec::with_capacity(8);
let mut grown: Vec<u32> = Vec::new();
let cap_before = planned.capacity();

Interactive Tools for This Topic

FAQ

What does Preallocate Vec Capacity Before Pushing print when run?
Execute the whole file; each printed line is prefixed with a label like `grow needed at len`, `grown: len`, `planned: len`.