Sub topic 3
Split Large Rust Crates to Speed Up Builds
Assume basic Rust syntax, ownership, Cargo commands, and Cargo.toml. The main idea is to reduce how much code Cargo must rebuild and how much machine code rustc must generate.
Split Large Crates into a Workspace
A Cargo workspace groups several related crates. Put stable, shared code in one crate and application-specific code in another:
[workspace]
resolver = "2"
members = ["app", "core", "storage"]
[workspace.dependencies]
serde = { version = "1", default-features = false, features = ["derive"] }A change in app can then avoid rebuilding unchanged core and storage code. Cargo can also compile independent crates in parallel.
Taming Monomorphization
Monomorphization is the compiler’s process of creating a specialized copy of generic code for each concrete type. It can improve runtime speed, but many instantiations increase compile time and binary size.
Keep generic wrappers small and move repeated work into a non-generic function:
use std::io;
use std::path::Path;
pub fn read_file<P: AsRef<Path>>(path: P) -> io::Result<String> {
read_file_inner(path.as_ref())
}
fn read_file_inner(path: &Path) -> io::Result<String> {
std::fs::read_to_string(path)
}Fewer Test Binaries
Each integration test file becomes a separate test binary. Many large integration-test files can therefore repeat compilation and linking. Group related tests when practical, and keep shared test helpers in a library or test-support crate.
Shared Build Caches
sccache stores compiler results and can share them across clean builds or machines. A shared target directory also avoids duplicate artifacts when several workspace commands use the same profile.
# .cargo/config.toml
[build]
rustc-wrapper = "sccache"Cache Builds in CI
Cache Cargo’s registry, Git checkout, and target artifacts with a key based on the operating system, Rust toolchain, and lockfile. Include the lockfile hash so dependency changes invalidate stale results.
Tune Release Builds
opt-level, codegen-units, and LTO trade build time against runtime speed and binary size. More codegen units usually compile faster. LTO can improve optimization but makes release builds slower.
Nightly Options
Nightly Rust offers experimental parallel front-end compilation and the Cranelift code-generation backend. These can help specific projects, but they require testing because availability and performance vary.
Exercise
Which change should you try first when one workspace crate rebuilds after every edit?
Show answer
Move stable or unrelated code into separate workspace crates, then measure whether the changed crate rebuilds alone.