Search code examples
rustvectorallocation

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

  • 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.