with_capacity
- Rust course
- Beginner
- Lesson 98/115
- 4 min
Reserve capacity up front with with_capacity for better performance.
with_capacity
A vector's length (len) is the number of elements in it; its capacity is how many elements it can hold without allocating again. When capacity runs out, the vector allocates a larger area and moves the elements. If you know how many elements are coming, allocating up front avoids these moves:
let mut v = Vec::with_capacity(10);
for i in 0..5 { v.push(i); }
println!("{} {}", v.len(), v.capacity() >= 10); // 5 truereserve and shrink_to_fit
Capacity can be managed on an existing vector too:
let mut v: Vec<u8> = Vec::new();
v.reserve(1000); // room for at least 1000 more elements
v.extend([1, 2, 3]);
v.shrink_to_fit(); // brings capacity close to the lengthGrowth usually doubles the capacity, which makes push O(1) on average. Exact capacity values are an implementation detail; your code should rely only on the "at least" guarantee.
Practice Vector with capacity
Create a vector with Vec::with_capacity(10) and push i * i for each i in 0..5. Print the length, the result of capacity() >= 10 and the vector on one line.
Starter code
fn main() {
// buraya yaz
}Sample solution
fn main() {
let mut v = Vec::with_capacity(10);
for i in 0..5 {
v.push(i * i);
}
println!("{} {} {:?}", v.len(), v.capacity() >= 10, v);
}Expected output
5 true [0, 1, 4, 9, 16]
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is <code>len()</code> after <code>Vec::with_capacity(100)</code>?
- 1
- Undefined
- 0 Correct answer
- 100
Explanation: with_capacity only reserves space, it doesn't add elements; v[0] still panics.
2 Reserve space
let mut v = Vec::____(10);
let mut v = Vec::with_capacity(10);
Explanation: with_capacity reserves room for the given number of elements up front.
3 Concept and meaning
| Term | Meaning |
|---|---|
len() |
Number of elements |
capacity() |
Reserved space |
reserve(n) |
At least n more |
shrink_to_fit() |
Releases extra space |