Enum Memory Layout

Enums have some memory overhead. To know which variant is being represented, Sway stores a one-word (8-byte) tag for the enum variant.

The space reserved after the tag is equivalent to the size of the largest enum variant. To calculate the size of an enum in memory, add 8 bytes to the size of the largest variant.

Examples

The following examples consist of enums with two variants.

The largest variant for Example One is the u64 and b256 for Example Two.

Example One

The size of enum T is 16 bytes, 8 bytes for the tag and 8 bytes for the u64.

pub enum T {
    a: u64,
    b: (),
}

Instantiating the u64 type will take up 16 bytes.

    let a = T::a(42);

Instantiating the unit type will take up 16 bytes.

    let b = T::b;

Example Two

The size of enum K is 40 bytes, 8 bytes for the tag and 32 bytes for the b256.

pub enum K {
    a: b256,
    b: u64,
}

Instantiating the b256 type will take up 40 bytes.

    let a = K::a(0x0000000000000000000000000000000000000000000000000000000000000000);

Instantiating the u64 type will take up 40 bytes.

    let b = K::b(42);