How to reduce size of Cargo projects?

One thing I’ve found seriously cumbersome is the size of Cargo projects for each of my programs. While I understand the idea of containing all necessary files for the program with the program to aid portability, when developing or just messing around with Rust code, especially when using things like Piston’s graphics crates, the size of the projects can become gigabytes each.
Is there a way to have Cargo Projects store their crates and other large dependencies outside of the project folder, and share that with other Cargo Projects that use the same crate version etc.?

1 Like

https://github.com/mozilla/sccache is a start. Makes compilation faster. I’m not sure if it makes the actual executable result smaller

Check out min-sized-rust and this great blog post.

I have found cargo-bloat very useful for analyzing binary size. The biggest offenders are often surprising; clap will easily be most of the bloat in a trivial app.

As a concrete example, I used cargo-bloat to determine one source of unnecessary code in my application was using goblin::Object when in fact I only needed goblin::elf. The net effect was including code for all of the various object file formats supported by goblin, but totally ignored by my project.

You can also enable lto or thin-lto on the release profile to help eliminate dead code. Other tricks for reducing binary size are listed here: https://github.com/johnthagen/min-sized-rust

I looked through the Cargo Book, and I may have found a way to a solution, but I’m not able to test it right now
https://doc.rust-lang.org/cargo/reference/specifying-dependencies.html#specifying-path-dependencies

There are a few different “sizes” of Cargo projects:

  1. Size of temporary files ./target/. Apart from produced executables, all of target/ is temporary garbage.

    There’s not much you can do about the temporary garbage part. sccache won’t make it smaller (and it’ll need its own cache). path dependencies don’t affect it at all. You might disable incremental compilation to make this dir a bit smaller, but it’s a very bad idea, as it will make compilation much slower. My suggestion is to just accept that target/ is going to contain gigabytes of temporary files.

    The whole dir can be rebuilt, so you can keep deleting target/ dirs whenever you’re low on disk space.

  2. Size of Cargo’s index and caches in ~/.cargo/. Cargo needs to have an index (that’s over 25000 files), which can’t be avoided. And it needs to check out/unpack dependencies for the build. These are shared between all projects.

    You can delete ~/.cargo/registry/cache/ and ~/.cargo/registry/src when you run low on disk space.

  3. Size of executable files produced. Build with --release, enable LTO, run strip.

2 Likes

Crates that live in a workspace all share the same target directory.

this right here is exactly what I was looking for, thanks