On used crates and compiled executable sizes/times

In my project, there are 15-20 sub-crates total. Many of the crates have duplicate dependencies, and some have dependencies that are equivalent in name but different in version. I have a few questions:

[0] Do crates with duplicate, equal-versioned dependencies get compiled only once? Does having more than n > 1equal crates increase the compiled artifact?

[1] If I create a "root crate" that has all the dependencies I need, and then re-import these for the other 15-20 crates to use, will this save compile-time and minimize the output compiled artifact?

Cargo will only duplicate dependencies if they are semver incompatible.

For example, if one of your crates uses num 0.2.0 and another crate uses num 0.2.1, Cargo will use num 0.2.1 for both.

If one of your crates uses num 0.2.0 and another crate uses num 0.3.0, however, you will have both versions in your final compiled artifact (which is unavoidable, because they could have completely different APIs).

1 Like

That's good to know, thanks. Would you then recommend that I create a "root crate" that imports everything I use, and then re-import from other crates?

No, I don't really see a benefit to that. It won't improve your compile times or output size, since you'd still be pulling in the exact same dependencies either way, and they don't tend to get rebuilt unless they change/unless you delete the target folder.

What might help is using a Cargo workspace, as that makes all of your sub-crates share a Cargo.lock and a target folder. That way, their dependencies will stay in sync/compatible, and you won't have to build all the dependencies from scratch if you try to build one of the subcrates in isolation.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.