pub const fn cold_path()🔬This is a nightly-only experimental API. (
cold_path #136873)Expand description
Hints to the compiler that given path is cold, i.e., unlikely to be taken. The compiler may choose to optimize paths that are not cold at the expense of paths that are cold.
Note that like all hints, the exact effect to codegen is not guaranteed. Using cold_path
can actually decrease performance if the branch is called more than expected. It is advisable
to perform benchmarks to tell if this function is useful.
§Examples
#![feature(cold_path)]
use core::hint::cold_path;
fn foo(x: &[i32]) {
if let Some(first) = x.get(0) {
// this is the fast path
} else {
// this path is unlikely
cold_path();
}
}
fn bar(x: i32) -> i32 {
match x {
1 => 10,
2 => 100,
3 => { cold_path(); 1000 }, // this branch is unlikely
_ => { cold_path(); 10000 }, // this is also unlikely
}
}This can also be used to implement likely and unlikely helpers to hint the condition rather
than the branch:
#![feature(cold_path)]
use core::hint::cold_path;
#[inline(always)]
pub const fn likely(b: bool) -> bool {
if !b {
cold_path();
}
b
}
#[inline(always)]
pub const fn unlikely(b: bool) -> bool {
if b {
cold_path();
}
b
}
fn foo(x: i32) {
if likely(x > 0) {
println!("this branch is likely to be taken");
} else {
println!("this branch is unlikely to be taken");
}
}