When I create a vector, the length and the capacity are the same. What is the difference between these methods?
fn main() {
let vec = vec![1, 2, 3, 4, 5];
println!("Length: {}", vec.len()); // Length: 5
println!("Capacity: {}", vec.capacity()); // Capacity: 5
}
Growable vectors reserve space for future additions, hence the difference between allocated space (capacity) and actually used space (length).
This is explained in the standard library's documentation for Vec
:
The capacity of a vector is the amount of space allocated for any future elements that will be added onto the vector. This is not to be confused with the length of a vector, which specifies the number of actual elements within the vector. If a vector's length exceeds its capacity, its capacity will automatically be increased, but its elements will have to be reallocated.
For example, a vector with capacity 10 and length 0 would be an empty vector with space for 10 more elements. Pushing 10 or fewer elements onto the vector will not change its capacity or cause reallocation to occur. However, if the vector's length is increased to 11, it will have to reallocate, which can be slow. For this reason, it is recommended to use Vec::with_capacity
whenever possible to specify how big the vector is expected to get.
len()
returns the number of elements in the vector (i.e., the vector's length). In the example below, vec
contains 5 elements, so len()
returns 5
.
capacity()
returns the number of elements the vector can hold (without reallocating memory). In the example below, vec
can hold 105
elements, since we use reserve()
to allocate at least 100 slots in addition to the original 5 (more might be allocated in order to minimize the number of allocations).
fn main() {
let mut vec = vec![1, 2, 3, 4, 5];
vec.reserve(100);
assert!(vec.len() == 5);
assert!(vec.capacity() >= 105);
}