I have a method, which takes 2 params: reader and dependency vector. Sometimes there no dependencies, so I should pass empty vector. I am not sure if this is optimized, so I have two questions:
Does it correct, that creating empty Vec<u8> pretty often is not optimized or the memory taken is pretty insignificant and I should not worry ? I tried btw to use Option<Vec<u8>> but it seems the memory taken is same. I used this snippet to measure that:
use std::mem::size_of;
fn main() {
println!("Size of Vec<u8>: {}", size_of::<Vec<u8>>());
println!("Size of Option<Vec<u8>>: {}", size_of::<Option<Vec<u8>>>());
let none: Option<Vec<u8>> = None;
println!("Size of None (Option<Vec<u8>>): {}", size_of_val(&none));
}
fn size_of_val<T>(val: &T) -> usize {
size_of::<T>()
}
If the solution can be optimized, how to do this in better way ? I mean, how to avoid allocating 24 bytes for each empty vector when there no dependencies I have to pass ?
Note that the 24 bytes will be on the stack or in registers, where it's very fast to "allocate". In fact usually "allocate" is used to mean allocating on the heap, where it's generally much slower.
To actually avoiding having to use stack space for the Vec you'll have to write a function that takes the vec and one that doesn't.
That's the size of the Vec itself (the pointer-capacity-length triple), which is constant. It has nothing to do with the size of the allocated heap buffer.
It's at leastvec.capacity() * size_of::<T>(). That's what the Vecrequesed from the allocator; the allocator itself may make a larger allocation. That's not something that is possible to query outside of very specific (often, platform-specific) situations.