Question about memory allocation

Hi Community !

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:

  1. 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>()
}
  1. 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 ?

Could somebody explain me that ?

Empty Vec does not (heap) allocate (I think that this holds for every collection type in standard library).

2 Likes

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.

3 Likes

I fixed the example above:

fn main() {
    let empty_vec: Vec<u8> = vec![];
    println!("Size of Vec<u8>: {}", size_of_val(&empty_vec));

    // ...
}

it shows 24 bytes for empty vector

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.

could you tell how to correctly get the size allocated on memory heap ?

It's at least vec.capacity() * size_of::<T>(). That's what the Vec requesed 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.

3 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.