13/09/2022
[Embedded C Optimization]
In IF-ELSE statements, you basically check on the IF condition. If that condition is true, the IF block will be executed and the ELSE block will be skipped. Surely, if the condition is false, the ELSE block will be executed and the IF block will be skipped..
You may think that, in both cases, performance is the same. Well, it's not. Otherwise, this post won't come to existence XD.
Performance-wise, it's preferable that the IF block gets executed. This is due to CPU pipeline behavior. The pipeline was firstly introduced to boost the CPU performance by fetching next instructions while the CPU is executing the current instruction. By default, the pipeline will fetch the instructions of IF block. Hence, if the IF block gets executed then all is fine. On the other hand, if the ELSE block is executed, the pipeline will be flushed and refilled with ELSE instructions.
This is why it's preferable that the IF block gets executed. So, what you should choose the IF condition such that it will be more likely to evaluate to TRUE.
Of course, there are different optimizations on compiler and hardware levels that can avoid pipeline flushing by branch prediction. However, you should just be a good player and try to do more right than wrong..
Hopefully, this was clear, correct and informative.