Answer#
Compile time in Rust comes from three places: type checking and borrow checking, code generation (generic code is generated again for each type it is used with), and optimisation. On top of that, a first build compiles all your dependencies from source. Later builds are incremental, but a release build with link-time optimisation is slow by design.
You cannot change how much work the compiler does, but you can avoid doing it. The answers below are independent measures; the first is the one that changes your day-to-day most.
Common mistakes#
- Running a full
cargo buildto see whether the code compiles.cargo checkstops before code generation and gives the same errors. - Measuring compile time of the debug build and concluding that Rust is slow at everything. Debug builds skip optimisation on purpose.
- Turning on
ltofor development builds. Keep it in[profile.release].
Related questions#
Why does the first build take so long?#
It compiles every dependency, including large ones such as an async runtime or a web framework, from source. Cargo keeps the results in target, so the second build is much faster until you run cargo clean or change the compiler version.
Does adding more dependencies slow the build?#
Yes, each one adds compile time and often more transitive dependencies. cargo tree shows what you pull in.
Sources#
- The Cargo Book, "Timings": https://doc.rust-lang.org/cargo/reference/timings.html
- The Cargo Book, "Environment variables" (
CARGO_TARGET_DIR): https://doc.rust-lang.org/cargo/reference/environment-variables.html