4 ms·
What is bit-wise copied is the pointer to the memory. I.e. a `HashMap` struct, or `Vec` struct don't directly contain the data. For example the `Vec` is defin
by dathinab 6y ago
What is bit-wise copied is the pointer to the memory.
I.e. a `HashMap` struct, or `Vec` struct don't directly contain the data.
For example the `Vec` is defined internally as something similar to:
`struct Vec<T> { data: *mut [T], capacity: usize, len: usize, marker: PhantomData<T> }`
(Slightly simplified, not actual Vec type).
So a move of a Vec copies at most 3 usize (24 bytes on 64bit systems), similar thinks apply for a HashMap.
Additionally the copy can often be elided through compiler optimizations.
As a interesting side note a new empty Vec/HashMap will not actually allocate any memory, only once elements get added it will start doing so. This is why it crates vec's of vecs of length 1. Or else it wouldn't need to do "number of element" free calls.
- tsimionescu 6y agoSo the Vec type is not storing data on the stack, like C++'s std::vector can?
- cesarb 6y agoExactly, neither Rust's Vec nor Rust's String (which is actually a Vec in disguise) store data within the struct itself, it's always stored in an external allocation. This is intentional, to avoid extra branches on whether the data is inline or not. If you have a lot of small vectors, and using less memory is more important for your use case than avoiding the extra branches, there are alternatives like https://crates.io/crates/smallvec https://crates.io/crates/smallvec that you can use.