#Rustlang has a #[cold] optimization hint for rarely-called functions.

  • Cold functions use a custom calling convention that uses fewer instructions at the caller's side, so it reduces size of programs that may have many calls to cold functions (great for error handling).

  • Cold functions may be placed in a separate section of the executable, to help instruction caches contain only hot functions.

  • If a conditional branch (if/else, or a pair of match arms) contains a call to a cold function, it's marked as unlikely to be taken, making the optimizer prioritize performance of the other branch (this hint is similar to profile-guided optimization).

  • Cold functions are usually not inlined, but you can add #[inline(never)] to be sure.

#[cold]
#[inline(never)]
fn handle_error(err: &dyn Error) -> ! {
}

impl MyError {
    #[cold]
    pub fn new() -> Self {
    }
}

impl fmt::Debug for T {
    #[cold]
    fn fmt(&self, …)
}