In C, you can define two interesting macros - likely() and unlikely(). Here’s what they would do and how they could make code performant…
These macros would wrap GCC’s __builtin_expect() function to give hints to the compiler about which branch of a conditional statement is more probable. When you write if(likely(x > 0)), you’re telling the compiler “this condition will almost always be true.”
The compiler uses this hint for branch prediction optimization. It arranges the assembly code so the likely path executes without taking a jump instruction, keeping the processor pipeline flowing smoothly and improving cache locality.
The Linux kernel uses these extensively - likely() appears over 3,000 times and unlikely() over 14,000 times in the codebase. The Linux ftrace tracer saw up to 20% performance improvement by adding proper likely/unlikely hints.
In practice, you might see 5-15% performance improvement in hot paths where branches are predictable.
But modern CPUs are already pretty good at predicting branches on their own. If you guess wrong and mark something as likely when it’s not, you can make performance worse.
So, we should not blindly add these everywhere for every single if in the code. They should be used in critical loops where you know the pattern and the branch happens millions of times per second.
Use them rarely, profile the code, and only apply it where the branch probability is genuinely skewed (90%+ in one direction).
Hope this helps.