https://ziggit.dev/t/about-branchhint/7408/6
https://github.com/ziglang/zig/issues/21148
https://ziglang.org/documentation/master/#branchHint
https://github.com/ziglang/zig/blob/master/lib/std/builtin.zig#L981
/// This data structure is used by the Zig language code generation and
/// therefore must be kept in sync with the compiler implementation.
pub const BranchHint = enum(u3) {
/// Equivalent to no hint given.
none,
/// This branch of control flow is more likely to be reached than its peers.
/// The optimizer should optimize for reaching it.
likely,
/// This branch of control flow is less likely to be reached than its peers.
/// The optimizer should optimize for not reaching it.
unlikely,
/// This branch of control flow is unlikely to *ever* be reached.
/// The optimizer may place it in a different page of memory to optimize other branches.
cold,
/// It is difficult to predict whether this branch of control flow will be reached.
/// The optimizer should avoid branching behavior with expensive mispredictions.
unpredictable,
};
none
likely
unlikely
cold
unpredictable
none
- 无提示// 编译器自行决定优化策略
if (condition) {
// 没有特殊优化提示
}
likely
- 很可能执行// 告诉编译器这个分支很可能被执行
if (@branch(.likely, hot_path_condition)) {
// 这里的代码会被优化器重点关注
frequently_executed_code();
}
unlikely
- 不太可能执行// 告诉编译器这个分支不太可能被执行
if (@branch(.unlikely, error_condition)) {
// 错误处理代码,不会被高度优化
handle_error();
}
cold
- 几乎不会执行// 极少执行的代码路径
if (@branch(.cold, rare_debug_condition)) {
// 这部分代码可能被放到内存的远端位置
debug_panic("This should never happen");
}
unpredictable
- 难以预测