Sub topic 5
Incremental compilation and what invalidates it
This chapter assumes you can build and test a Cargo project and read Cargo.toml. It also assumes you have met the dev and release profiles from the previous chapter. Here you will learn how incremental compilation works, why a small edit can still trigger a large rebuild, and how to tell when it is helping.
What incremental compilation does
Without incremental compilation, rustc treats a crate as one unit. Any change makes it redo every step for the whole crate: parse, type check, generate code, and optimize.
With incremental compilation, rustc saves intermediate results between runs. On the next build it compares the new source with what it saved. It reuses the results that are still valid and redoes only the work that depends on your change.
Cargo turns this on by default for the dev profile and off by default for release. The reason is that the saved data costs time and disk space to write, and it can leave less optimized code. Release builds favor the best output over rebuild speed.
The cache lives in the target directory:
target/debug/incremental/<crate-name>-<hash>/Each crate you are building gets its own folder. Only crates in your workspace use incremental compilation. Dependencies from crates.io are built without it, because they rarely change.
How rustc decides what to redo
rustc is built on a query system. Each step of compilation is a query, such as "what is the type of this function?" or "what is the machine code for this item?". A query reads inputs, which may be other queries, and returns a result.
When rustc runs, it records a dependency graph. The graph shows which query results were used to compute each other result. It also stores a fingerprint, which is a hash of each result.
On the next build, rustc uses a strategy known as red-green marking:
- It starts from the source files and checks which inputs changed.
- For each query that depended on a changed input, it tries to recompute the result.
- If the new result has the same fingerprint as before, the query is marked green. Everything that depended only on it can be reused.
- If the fingerprint differs, the query is marked red. Queries that depend on it must be recomputed.
The key point is that a change stops spreading when a recomputed result comes out identical. Adding a comment, for example, changes the file but leaves the type information the same. Most of the work stays green.
The unit of reuse: codegen units
Code generation is where most of the time goes. rustc splits a crate's generated code into codegen units (CGUs). Each CGU is handed to LLVM separately. With incremental compilation on, rustc uses many more CGUs than it does otherwise, 256 by default for dev builds. Smaller units mean that a change touches less code, so LLVM can reuse more of the earlier object files.
This is why incremental builds are fast when you edit the body of one function. Only the CGU holding that function needs new machine code. The rest are loaded from the cache.
Two costs remain after rustc finishes:
- The linker still runs on every build. It must combine all the object files into a binary. Incremental compilation does nothing for this step, so a large project can still feel slow after a one-line change. The linking chapter covers this.
- The front end still does some work for the whole crate, such as loading the saved graph and checking which parts are affected.
What invalidates the cache
Incremental compilation is a heuristic. It works well in the common case, but several things can make rustc throw away the cache or redo much more work than you expect.
Changes to public signatures and types
If you change a function body, only that function is red. If you change its signature, every function that calls it becomes red too, because its inputs have changed. Changing a widely used struct, trait, or type alias has the same effect, and the spread can reach most of the crate.
Practical consequences:
- Edits inside function bodies are cheap.
- Edits to types, trait definitions, and signatures that many modules use are expensive.
- Changing a
constor astaticthat is used widely can cascade the same way.
Changes to flags, profile, or toolchain
The cache is tied to the exact compiler and its settings. These all start a full rebuild of the affected crates:
- Updating the Rust toolchain, including switching between stable and nightly.
- Changing
RUSTFLAGS, or changing flags in.cargo/config.toml. - Changing profile settings such as
opt-levelordebug. - Changing enabled Cargo features.
Alternating between two sets of flags is a common trap. A typical case is running cargo check or an IDE tool with different RUSTFLAGS than your terminal builds. Cargo keeps separate fingerprints, so each switch rebuilds from scratch, and the two tools can keep invalidating each other's work.
Dependency changes
If a dependency is rebuilt, every crate that uses it is rebuilt. A change to Cargo.lock, such as running cargo update or adding a crate, can therefore cost a lot of time. Version bumps rebuild the crate that changed and everything above it in the dependency graph.
Build scripts and environment variables
A build.rs script that Cargo considers changed forces the crate to rebuild. By default, Cargo reruns a build script when any file in the package changes. A script that does not declare what it depends on can trigger needless rebuilds. Use cargo:rerun-if-changed to narrow this:
// build.rs
fn main() {
// Rerun only when this file changes, not on every source edit.
println!("cargo:rerun-if-changed=schema.sql");
println!("cargo:rerun-if-env-changed=APP_VERSION");
}Code that reads environment variables with env! or option_env! has a similar effect. rustc tracks those variables, and a change to one rebuilds the code that reads it.
Corrupted or stale cache
Sometimes the incremental directory ends up in a bad state, for example after a crash or when two builds write to it at once. Signs include odd errors that disappear after a clean build, or a build that always redoes everything. The fix is to delete the cache for the crate or run cargo clean.
Seeing what rustc reuses
You can ask rustc to print how much it reused. This needs the nightly compiler, but it only reads information and does not change your code:
RUSTFLAGS="-Z incremental-info" cargo +nightly buildThe output reports how many CGUs were reused and how many were rebuilt. A healthy edit-compile loop reuses most of them.
On stable, you can use cargo build --timings from the measuring chapter. Compare a first build, a build with no changes, and a build after a one-line edit. If the one-line edit takes nearly as long as the first build, something is invalidating the cache.
A simple experiment shows the effect:
- Run
cargo buildand note the time. - Run it again with no changes. It should finish almost at once.
- Edit the body of a function and build. The time should be short.
- Change the signature of a widely used function and build. The time should be noticeably longer.
- Run
cargo clean -p your_crate, then build, and compare with step 1.
When to turn it off
Incremental compilation is almost always right for local development. There are a few cases where you should disable it:
- CI builds that start from a fresh checkout. The cache is empty, so writing it is wasted work. Set
CARGO_INCREMENTAL=0in the environment. - Release builds, which already default to off.
- Builds that you cache and restore between runs, if the incremental data is large and changes on every commit. Caching it can cost more in upload and download time than it saves.
You can set the behavior for a profile in Cargo.toml:
# Cargo.toml
[profile.dev]
incremental = true
[profile.release]
incremental = falseThe CARGO_INCREMENTAL environment variable overrides the profile setting. Setting it to 0 turns the feature off, and 1 turns it on.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Using different `RUSTFLAGS` in the IDE and the terminal | Each tool rebuilds what the other built | Make both use the same flags, or give the IDE its own target directory |
| Build script without `rerun-if-changed` | The script and the crate rebuild after any edit | Declare the files and variables the script reads |
| Keeping `incremental` on in a clean CI build | Extra time spent writing a cache nobody reads | Set `CARGO_INCREMENTAL=0` |
| Editing a core type in the middle of a large crate | Large part of the crate becomes red | Move shared types into a small, stable crate |
| Expecting faster linking from incremental builds | Link time is unchanged | Use a faster linker |
Exercise
You edit a comment in one file and the following cargo build finishes almost instantly. Then you add a new parameter to a function that is called from forty places, and the next build is much slower. Explain both results using the red-green model.
Show answer
The comment edit changes the file, so rustc recomputes the queries that read it. The results come out identical, so their fingerprints match. Those queries are marked green, and everything else is reused from the cache. Adding a parameter changes the function's signature, so the fingerprint of its type query differs and it is marked red. The forty callers depend on that query, so they are marked red and recomputed. Their CGUs also need new machine code from LLVM, so the build takes longer.
Exercise
A CI job always starts from a clean checkout and has target/debug/incremental enabled by default. What would you change, and why?
Show answer
Set CARGO_INCREMENTAL=0 for that job. With no cache to reuse, incremental compilation only adds the cost of writing saved state, and it can produce slightly less optimized code. Disabling it makes the build somewhat faster and the target directory smaller, which also helps if you cache that directory between runs.