Sub topic 7
The cost of proc macros and build scripts
This chapter covers two features that run code at build time: procedural macros and build scripts. Both can dominate a build without showing up in your own source files. It assumes you can read Cargo.toml, know what #[derive(...)] does, and have run cargo build --timings as described in the measuring chapter.
Why these two features are special
Most of your build is rustc compiling Rust source into machine code. Procedural macros and build scripts are different. Each one is a Rust program that must be compiled and then run before the code that depends on it can be built.
- A procedural macro (proc macro) is a compiler plugin. It is a library crate with
proc-macro = true. rustc loads it as a dynamic library and calls it with a stream of tokens. It returns new tokens.#[derive(Serialize)],#[tokio::main]andsqlx::query!are proc macros. - A build script is a file named
build.rsat the crate root. Cargo compiles it into an executable and runs it before compiling the crate. It can generate code, compile C sources, or print instructions for Cargo.
Both are compiled for the machine doing the build (the host), not for the target you are building for. The host/target split is where much of the hidden cost comes from.
Where proc macro cost comes from
Proc macros cost time in three places.
- Compiling the macro crate and its dependencies. Most proc macros depend on
syn(a Rust parser),quote(a code generator) andproc-macro2. With thefullfeature,synis large. The first build, and every clean build, pays for it. - Running the macro. Each use of a derive or attribute macro runs the macro's code during expansion. A macro that parses a big struct and emits many impls costs more than a small one.
- Compiling the code the macro generates. This is often the largest part. A derive can emit hundreds of lines per type, and rustc and LLVM must compile all of it. Generated code that is generic adds monomorphization cost too, which is covered in the generics chapter.
Proc macros also create a serialization point in the build. Cargo cannot compile a crate that uses a proc macro until the macro crate, and everything it depends on, is built. Build time then depends on how long this chain takes, not just on total CPU time.
Seeing the chain in the timings report
Run the timings report and look at the crates that start early and take a long time.
cargo build --timingsOpen target/cargo-timings/cargo-timing.html. Look for:
syn,proc-macro2,quoteand*-deriveor*-macroscrates on the critical path.- Bars labeled with
build script (run)orbuild script (compile). These appear as separate units. - Long gaps where many crates are waiting on one of them.
The report shows a unit's duration, plus when it started and when its dependents could start. A crate that takes only a few seconds but blocks twenty others is still worth fixing.
Reducing proc macro cost
Count your uses first
Run cargo tree to see which proc macro crates you pull in, and who requires them.
# Show who depends on syn and which versions are present
cargo tree -i syn
# Show duplicate crate versions
cargo tree -dTwo versions of syn (for example 1.x and 2.x) mean both are compiled. Duplicates often come from one old dependency. Updating or replacing it removes a whole proc macro stack from the build.
Trim features
serde ships derive as an optional feature. If a crate in your workspace needs only Serialize on a few types, that is fine. But if a library enables derive just to use it in an example or a test, move that use to [dev-dependencies] so downstream users do not pay for it.
For your own proc macros, avoid the full feature of syn when you can. The default features parse items such as structs and enums, which is enough for most derives. full adds a parser for function bodies and expressions.
# Cargo.toml of a derive crate
[dependencies]
syn = { version = "2", default-features = false, features = ["derive", "parsing", "printing", "proc-macro"] }
quote = "1"
proc-macro2 = "1"Test the feature set by building. If the macro needs a feature you removed, the compiler errors name the missing item.
Do not add a macro for something a function does
A derive is the right tool for repetitive trait impls. It is a poor tool for a few lines of logic. Where a generic function, a plain macro_rules! macro, or a manual impl is short, avoid the proc macro dependency. A macro_rules! macro is expanded by rustc itself. It needs no separate crate and no host-side compile.
Share derives instead of repeating them
Every #[derive(Debug, Clone, Serialize, Deserialize)] on a large number of types generates code for each of them. If many types have the same shape, consider whether they should be one generic type. Alternatively, keep rarely used derives behind a feature, as in #[cfg_attr(feature = "serde", derive(Serialize))].
// Only pay for serde's derive code when the feature is on.
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[derive(Debug, Clone)]
pub struct Point {
pub x: f64,
pub y: f64,
}
fn main() {
let p = Point { x: 1.0, y: 2.0 };
println!("{:?}", p);
}For this to compile, Cargo.toml needs serde = { version = "1", optional = true, features = ["derive"] } and a serde feature. Without the feature, the program builds without the serde proc macro.
Measuring expansion
Use cargo expand (install with cargo install cargo-expand) to see what a macro emits. A derive that produces a large amount of code for a simple struct is a candidate for replacement. On nightly, -Zmacro-stats reports how many lines and bytes each macro generates.
cargo expand --lib some_module | wc -lWhere build script cost comes from
A build script adds cost in four ways.
- It is compiled as its own crate, with its own dependencies. A
build.rsthat depends oncc,bindgenorprost-buildcompiles those first. - It runs on every build in which it is invalidated. By default, Cargo reruns a build script if any file in the package changes. That is very conservative.
- Its output can change the main crate's inputs, such as
cargo:rustc-cfgorcargo:rustc-link-lib. A change in output forces a rebuild of the crate. - It can do heavy work itself. Compiling C code with
cc, or runningbindgenover large headers, may take longer than all of your Rust code.
Use `rerun-if-changed`
Without any rerun-if-* line, Cargo runs the script when any file in the package changes. Editing a README can cause it. Tell Cargo exactly what matters.
// build.rs
fn main() {
// Rerun only if this file or the build script itself changes.
println!("cargo:rerun-if-changed=build.rs");
println!("cargo:rerun-if-changed=proto/service.proto");
// Rerun if this environment variable changes.
println!("cargo:rerun-if-env-changed=MY_FEATURE_FLAG");
}Once you emit any rerun-if-changed line, Cargo stops its default scan of the whole package and tracks only the paths you list. Forgetting a path that the script reads means stale output. This is the main risk of the technique, so list every input.
On newer Cargo versions you can write cargo::rerun-if-changed=... with a double colon. The single-colon form still works.
Avoid build scripts you do not need
Common uses that have lighter alternatives:
- Reading the version or git hash. Use
env!("CARGO_PKG_VERSION"), which needs no script. - Checking the target OS. Use
#[cfg(target_os = "linux")], which needs no script. - Detecting a compiler feature. Use
rust-versioninCargo.tomland a minimum supported Rust version instead. - Generating code from a schema. Consider checking the generated file into the repository and regenerating it by hand or in CI. Then ordinary builds do not need
prost-buildorprotocat all.
The last option trades convenience for build speed. You must remember to regenerate. A CI check that regenerates and compares to the committed file helps catch drift.
Prebuilt and system libraries
Crates such as openssl-sys compile or link C code in a build script. Where it fits, use a system library through pkg-config rather than compiling a vendored copy. A vendored build is more portable, but it can add a minute or more to clean builds. Weigh this per project. Libraries written in pure Rust, such as rustls for TLS, avoid the C compile step, though they bring their own cost.
Optimizing proc macros and build scripts in dev builds
Build scripts and proc macros run at build time, so in a dev build their own speed is the speed of unoptimized code. A build script that does heavy work, such as parsing a large schema, can be very slow at opt-level = 0. You can optimize only the build-time code without touching your own crate.
# Cargo.toml
[profile.dev.build-override]
opt-level = 3
debug = falsebuild-override applies to build scripts, proc macros, and their dependencies. Setting opt-level = 3 makes them cost more to compile but run faster. This pays off when macro expansion or script execution is long, and loses when they are tiny. Measure with --timings before and after. The release profile already defaults build overrides to opt-level = 0, so the setting matters most when you care about a heavy script.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Build script reruns on every build | No `rerun-if-changed`, or it lists a file the script itself writes inside the source tree | Write output only to `OUT_DIR` and list only real inputs |
| Generated code is stale after an edit | A `rerun-if-changed` line omits an input file | List every file the script reads |
| Two copies of `syn` in `cargo tree -d` | One dependency still uses `syn` 1.x | Update or replace that dependency |
| Cross-compiling fails in a macro crate | Proc macros are built for the host, but a target-only dependency was used | Keep the macro crate free of target-specific code |
| Rust Analyzer is slow after a macro change | The macro is re-expanded on each edit | Disable or limit proc macro expansion for heavy crates in editor settings |
Choosing what to change
Work in this order, and stop when the timings report no longer shows these units on the critical path.
- Find proc macro and build script units in
cargo build --timings. - Remove duplicate
synversions and unneeded macro dependencies. - Add precise
rerun-if-changedlines to your own build scripts. - Replace build scripts and macros that a
cfg,env!, or a plain function can do. - Try
build-overrideonly if the script or macro itself runs for a long time.
Exercise
A crate has a build.rs with no cargo:rerun-if-changed lines. It reads schema.json and writes generated.rs to OUT_DIR. Every edit to any source file reruns the script. Write the single line you would add so it reruns only when schema.json changes, and name one extra line you should keep so that edits to build.rs are also picked up.
Show answer
Add println!("cargo:rerun-if-changed=schema.json");. Also keep println!("cargo:rerun-if-changed=build.rs"); so that changes to the script itself trigger a rerun. Once any rerun-if-changed line exists, Cargo watches only the listed paths.
Exercise
cargo tree -d shows syn v1.0.109 and syn v2.0.87. Why does this slow a clean build, and what is the usual fix?
Show answer
Both versions are compiled, along with the proc macro crates that depend on each, and macro crates sit on the critical path. Find the dependency that still requires syn 1.x with cargo tree -i [email protected], then update it, replace it, or accept it if no newer release exists.