Binary Bloat: Monomorphization's Cost

The primary trade-off of Rust's monomorphization is increased binary size and longer compile times, as the compiler generates a separate, specialized copy of generic code for every unique type it's used with.

The top 3

  1. Rust Binary Size: How It Stacks Up: Rust's compiled binaries, when fully optimized, can be significantly smaller than C++ static executables (e.g., 256KB for Rust vs. 662KB for C++ in one benchmark). However, a default 'Hello World' Rust binary can be much larger than a C equivalent (e.g., 2.3MB vs. 14KB) due to static linking and included debug info by default. With dynamic linking and stripping, both Rust and C++ can achieve similar minimal sizes (around 16.5KB).
  2. Major Causes of Rust Binary Bloat: The primary factors contributing to Rust's larger binary sizes include: 1. **Monomorphization of generics:** Each unique type used with a generic function or struct results in a specialized copy of the code, leading to code duplication. 2. **Static linking:** Rust binaries typically statically link almost everything, including the standard library, embedding most dependencies directly into the executable. 3. **Debug symbols and panic machinery:** Even in release builds, Rust often includes debug information and extensive panic handling code by default, which adds significant size unless explicitly stripped or configured otherwise.
  3. Rust Binary Size: How It Compares to C, C++, Go: An unoptimized 'Hello World' in Rust can be 2.3-4.2MB, considerably larger than C's ~14KB. However, optimized Rust binaries can shrink to 256KB (static) or 16.5KB (dynamic), often outperforming C++ static builds (662KB) and matching C++ dynamic builds. Go binaries typically range from 2MB to 11.5MB.

Sources

Open the full topic