Pros and cons of splitting out crates

Should I split my project up into lots of small crates (that may be useful externally), a la node/npm, or are there disadvantages to doing so? What kind of optimisations can (or can't) rustc do across crates?

On a conceptual level, I like my code modular and reusable. So, I'll try to create a lot of small crates. Since you can have multiple crates in one repository, it's very cheap to divide early and move crates into their own repo when they expand. This also let's you track dependencies on a more granular level.

Here's a bit of motivation (by someone who published over 600 modules to npm): (tl;dr don't need to remember as much, tests, every projects profits from optimizations to basic crates)

AFAIK, there are some difficulties with inlining across crates; but there is also stuff with LTO which sometimes helps but is other times considered bad.

1 Like

Don't forget that since crates are the compilation unit, more and smaller crates means that you're getting a more paralell compile.

1 Like

One of the disadvantages of splitting a crate into smaller crates is that there isn't function inlining across crates without #[inline], so possibly less optimization.

That's a good tip though: explicit #[inline] works across crates!

1 Like

Also note that generic functions and blanket trait implementations can be inlined across traits without any explicit annotations.

A question, if I embed a crate in another (use dependency with path = "xyz" how does cargo and treat that? Is it possible to publish the crate with a bundled dependency like this? I've never tried.

Yes. regex does this for regex-syntax:

1 Like