What does #[inline] do?

  Kiến thức lập trình

I have read The rust performance book extract after coming across an #[inline] but some points remain unclear to me (I might just be missing context/experience).

Does #[inline] have just performance implication and does not change the program behaviour in any case?

Can you come up with an easy example in which #[inline] worsens performance? Does it exist?

Does #[inline] have just performance implication and does not change the program behaviour in any case?

Yes. #[inline] is a hint for the optimizer. If it changes program behavior, you’d come across a miscompilation (or Undefined Behavior).

Can you come up with an easy example in which #[inline] worsens performance? Does it exist?

It’s hard to come with an example, because #[inline] is just a hint and the optimizer is free to ignore it. It is easier to come with an example where #[inline(always)] worsens performance (still a hint, but a stronger one), but even that is not trivial, because the impact is indirect: more instruction cache pressure (which will only show up in large programs, not in small examples), and other microarchitectural problems.

As a rule of thumb, put #[inline] on small functions that cross crate boundaries. If they don’t cross crate boundaries, this can help performance but often will be nop. If they are large, this can worsen performance or will be nop. #[inline(always)] and #[inline(never)] should almost never be used, the only exception being when you have a reason to believe you know better than the optimizer (for example, a very large function but that is only called with constant inputs that will make it optimize to small), and ideally this should come with a benchmark.

LEAVE A COMMENT