Skip to content
systemcoding.dev
Performance

Mark rarely called Rust error handlers with the cold attribute

Mark rarely called Rust error handlers with the cold attribute in Rust 1.80, so the optimiser moves them off the hot path.

1 min read
Summarize in AI

When a function exists only to handle a failure, tell the compiler it is rarely called. #[cold] on the function makes the optimiser assume any branch leading to it is unlikely and move the code away from the hot path.

cold.rsrust
#[cold]
#[inline(never)]
fn too_big(n: usize) -> i32 {
    eprintln!("too big: {n}");
    -1
}

fn check(n: usize) -> i32 {
    if n > 1000 {
        return too_big(n);
    }
    n as i32 * 2
}

fn main() {
    println!("{}", check(7));
    println!("{}", check(5000));
}
Text
14
too big: 5000
-1

#[inline(never)] keeps the handler from being inlined back into the hot function, which cold alone usually prevents but does not promise. The too big line goes to stderr, so it may appear in a different place relative to the stdout lines in a terminal. A function that always panics is already treated as cold by the compiler. Use the attribute on handlers, not on code that actually runs often, because a wrong hint makes the common path slower. See the Reference.

Taggedrust
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.