8.11 Inlining Functions

Inlining is an optimization where the compiler replaces a function call with the function's body to eliminate the overhead of the call.

  • In Rust: The compiler can automatically inline functions during optimization passes.
  • Attributes: You can suggest inlining using attributes, but the compiler makes the final decision.

8.11.1 Using the #[inline] Attribute

#![allow(unused)]
fn main() {
#[inline]
fn add(a: i32, b: i32) -> i32 {
    a + b
}
}
  • #[inline]: Hints to the compiler that it should consider inlining the function.
  • #[inline(always)]: A stronger hint to always inline the function.
  • Note: Overusing inlining can lead to code bloat.