How to Use cargo-bloat to Find What's Contributing to Binary Size

Use `cargo-bloat` to analyze your binary's size by running it as a wrapper around `cargo build`, which generates a report listing functions and crates sorted by their memory footprint.

Use cargo-bloat to analyze your binary's size by running it as a wrapper around cargo build, which generates a report listing functions and crates sorted by their memory footprint. This tool specifically identifies which symbols are consuming the most space, helping you target optimizations like stripping unused code or reducing generic monomorphization.

First, install the tool globally using cargo install cargo-bloat. Once installed, run it in your project directory to see a breakdown of the binary size by function:

cargo install cargo-bloat
cargo bloat --release --crates --no-std

The --release flag ensures you are analyzing the optimized binary, while --crates groups results by external dependencies, and --no-std excludes the standard library from the report to focus on your code and third-party crates. The output will display a table showing the symbol name, its size, and the percentage of the total binary it occupies.

If you need to drill down into specific crates or see the full disassembly, you can filter the output or use the --all flag to include everything. For example, to see the top 10 largest functions regardless of crate:

cargo bloat --release --all --top 10

Common findings include large generic functions that have been monomorphized multiple times or heavy dependencies like serde or regex pulling in unused features. If you see a specific function taking up excessive space, check if it can be moved to a separate crate to allow the linker to drop it if unused, or if generic parameters can be constrained to reduce code duplication.

For a quick check on the impact of stripping symbols, compare the size before and after running strip on the release binary, though cargo-bloat is better for identifying the root cause rather than just reducing the final size. The tool relies on llvm-symbolizer and rustc-demangle to provide readable function names, so ensure your system has these dependencies installed if you encounter garbled output.

By regularly running cargo bloat during development, you can prevent binary bloat from accumulating and make informed decisions about dependency selection and code structure.