Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Will an empty Vec which is never used still be allocated?

I have a program where I have a lot of struct types which have a Vec as a field, but in most cases the Vec never get’s used (the types are in a separate library which doesn’t know in advance which of types library users will want to add Vecs to). The example below illustrates the situation. I want to know whether the empty Vec in b will be allocated, or if the compiler is smart enough to know it doesn’t get used so doesn’t need an allocation. I suspect it will still be allocated, in which case I will wrap the Vec in an Option so that b can be created without needing to allocate a Vec, thereby avoiding many unnecessary allocations.

#[derive(Debug)]
struct Foo {
    message: String,
    vec: Vec<String>,
}

fn main() {
    let a = Foo {
        message: "Hello".to_string(),
        vec: Vec::new(),
    };
    dbg!(a.message);
}

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The compiler is likely not smart enough to eliminate the Vec, but it still won’t allocate as Vec::new() does not allocate:

The vector will not allocate until elements are pushed onto it.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading