10.5 Enums and Memory Layout
10.5.1 Memory Size Considerations
Even when variants contain different data types with varying sizes, the enum as a whole has a fixed size.
- Largest Variant: The size of the enum is determined by the largest variant plus some additional space for the discriminant (to track the active variant).
- Memory Usage: If variants have significantly different sizes, memory may be wasted.
Example:
#![allow(unused)] fn main() { enum LargeEnum { Variant1(i32), Variant2([u8; 1024]), } }
- The size of
LargeEnum
will be approximately 1024 bytes, even ifVariant1
is used.
10.5.2 Reducing Memory Usage
To reduce memory usage, you can use heap allocation for large data.
Example:
#![allow(unused)] fn main() { enum LargeEnum { Variant1(i32), Variant2(Box<[u8; 1024]>), } }
Box
Type: Allocates data on the heap, and the enum stores a pointer, reducing its size.- Trade-Off: Heap allocation introduces overhead but reduces overall memory usage.
Note: This approach is beneficial not just for stack space but for memory usage in general, especially when storing enums in collections like vectors.