Back to TILs

Rust enums cost

Something not immediately obvious but obvious after thinking about it for a minute is memory size of tagged unions.

Each Token will take up 40B + size of enum discriminant - 1B (tag) which will be aligned to 8B because entire structure needs to be aligned by the highest data type size (usize or String (ptr inside is 8B)) which is 8B.

struct Span {
    line: usize,   // 8 bytes
    column: usize, // 8 bytes
}

enum Token {
    Identifier {
        name: String,  // 24 bytes
        location: Span // 16 bytes
    },
    Number {
        value: i32,    // 4 bytes
        raw: String    // 24 bytes
    },
    If(Span),          // 16 bytes
}