Given the following code, why is the capacity
of each of the vectors 0 instead of chunk_size
?
#[test]
fn test() {
let chunk_size = 1024;
let data: Vec<Vec<u8>> = vec![Vec::with_capacity(chunk_size); 2];
assert_eq!(data[0].capacity(), chunk_size);
assert_eq!(data[1].capacity(), chunk_size);
}
Playground link: https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=0c40515b164044621c369adef1090c6e
Not all of them are zero, the second is 1024:
fn main() {
let chunk_size = 1024;
let data: Vec<Vec<u8>> = vec![Vec::with_capacity(chunk_size); 2];
dbg!(data[0].capacity(), data[1].capacity());
}
And if we increase the size of the outer vector, we can see it's always the last element which is 1024, and all others are zero.
Why is that?
That's because the vec![]
macro uses Clone
to fills the elements. To not clone more than needed, it clones all elements but the last and re-uses the element provided for the last (since it needs it for all others to clone from).
Cloning a Vec
does not consider the capacity. It only allocates enough elements to hold the length. This decision makes sense if you consider than capacity is not always intentional: many times, most of the times, it is just the leftover of growing the Vec
while pushing into it. So when we have a fresh new start, why allocate more than needed?