Description
This is proposal for a small feature, local and isolated. Could improve code readability.
Linux kernel uses macros likely
and unlikely
:
if (likely(x > 0)) { ... }
...
if (unlikely(y == NULL)) { ... }
These macros may improve performance a little bit and they serve as handy documentation.
Language Nim supports this functionality too, through its standard library ( https://nim-lang.org/docs/system.html#likely.t,bool ).
My proposal:
Add if+
and if-
into the language. if+
would signal that the path is rather likely, if-
will suggest the flow will not go this way.
if+ (x < 0) {
... // likely goes here
}
if- (err) {
... // unlikely
}
What is this good for:
- It gives hint to source code reader, hint which will be almost never found in the documentation. This hint is very short, intuitive, and doesn't require extra pair of parenthesis.
- It may slightly improve the performance, by rearranging instructions so that the likely path goes w/o jump, or by inserting hint for branch selector.
How it could be implemented:
- By doing nothing, just using it as documentation only feature.
- By using IR opcode
llvm.expect
. This is how clang implements__builtin_expect
, which is called bylikely
/unlikely
macros. (GCC also provides__builtin_expect
, MSVC has nothing similar.)
Performance effects of __builtin_expect
are hotly disputed on the internet. Many people claim programmers are invariably bad in such prediction and profile guided optimization will do much, much better. However, they never support their claim by benchmarks.
Even if performance is unaffected the documentation value remains. When one is stepping the code through debugger and the flow goes against the hint, one may be get more cautious a catch a bug.