A surprising enum size optimization in the Rust compiler
Published on: 2025-05-01 21:30:45
A surprising enum size optimization in the Rust compiler
Enums are one of the most popular features in Rust. An enum is type whose value is one of a specified set of variants.
/// Foo is either a 32-bit integer or character. enum Foo { Int(u32), Char(char), }
Values of type Foo are either integers (e.g. the variant Foo::Int(3) with a payload of 3 ) or characters (e.g. the variant Foo::Char('A') with a payload of 'A' ). If you think of structs as being the and combination of their fields, enums are the or combination of their variants.
This post is about a surprising optimization that the Rust compiler performs on the memory representation of enum values in order to make their memory usage smaller (spoiler: it’s not the niche optimization). In general, keeping values small can result in faster programs because values get passed around in CPU registers and more values fit in single CPU cache lines.
Generally the size of an enum is the size of the largest payload, plus some extra byt
... Read full article.