2

I replaced one occurrence of if/else with likely/unlikely which given me some improvement in performance as this executes many times. Now I would like to change all the occurrences of if/else with likely/unlikely. I use this code on only one target/OS.

Does this have any drawbacks to replace all if/else's ?

jabujavi
  • 477
  • 5
  • 15
Srikanth
  • 517
  • 3
  • 10
  • 29
  • You should replace only that conditions that have high probability to be true or false (that usually depends on data). However, you may try to collect branch misses statistics and change only that functions, which suffer from sub-optimal code. – myaut Apr 22 '15 at 08:30
  • 2
    Did you mean drawbacks rather than backdrops? A drawback is a potential problem, a backdrop is scenery in a theater presentation. – paxdiablo Apr 22 '15 at 08:30
  • I assume you are talking about gcc and kernel development. the likely/unlikely should be used only where you are absolutely sure the if will go on one branch > 90% of cases. However it is useless to do this to pieces of code that are not hotspots. So **profile** your application (if possible) and **only then** see how and where it should be accelerated. – bolov Apr 22 '15 at 08:32
  • 1
    this question will give answer to your question http://stackoverflow.com/questions/109710/likely-unlikely-macros-in-the-linux-kernel-how-do-they-work-whats-their – smali Apr 22 '15 at 08:34
  • Experience shows that programmers are notoriously bad at guessing which branches are taken; profile your code instead! – fuz Apr 22 '15 at 10:08
  • Tell me the name of the CPU where this optimization actually works. – Bogi Jul 06 '20 at 10:00

1 Answers1

3

As likely and unlikely usually are macros defined in some library and expanding to some __buildin...-commands, the only drawback you can expect is, that this might be harder to read.

Edit: But please - use it only in that cases, where you really expect a condition to be more likely than the alternative!

If some platform / library does not implement likely and unlikely or the implementation is wrong, you can easily #define it empty by yourself.

urzeit
  • 2,863
  • 20
  • 36