rustlanguage-lawyerinline

Why does Rust's standard library mark generic functions as #[inline]?


I'm was reading through parts of Rust's standard library as inspiration for a library I'm working on. I noticed that many functions are marked #[inline] despite them being generic. Here's a few examples.

To me this seems to contradict the dev guide, which explicitly states

You shouldn't need #[inline]:

  • On methods that have any generics in scope.

[..]

#[inline] can always be added later, so if there's any debate about whether it's appropriate feel free to defer it by removing the annotations for a start.

The reason for this guideline seems to be that generic functions are always available in the calling crate due to monomorphization, so #[inline] would not actually do anything.

So why does std do this? Is it

a) just an oversight / historical artifact

or

b) for a good reason that I don't understand?


Solution

  • This Rust issue laments that its not so simple.

    Summarizing: #[inline] on a generic function does not do nothing. It does impact where the generic is instantiated - once per crate vs once per codegen unit - which in turn impacts later optimization passes. This distinction can have measurable effects.

    The rule of thumb should still serve you well, but for maximum performance you may need to measure the impact of its introduction on well-used generics (just as you should measure before putting #[inline] on anything). There is not clear guidance there for determining which generics should be considered.