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.
Code
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
HAR Waterfall AnalyzerInspect HTTP Archive (HAR 1.2) JSON files locally to summarize total requests, status codes, MIME types, slowest calls, and timing waterfalls.Kubernetes Resource CalculatorCalculate per-pod and cluster CPU and memory requests, limits, QoS class, overcommit ratios, headroom, and node fit estimates for Kubernetes workloads.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
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`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.