I was wondering if there is a big performance difference in languages, whether you should put the more likely to be executed code in the if
or in the else
clause. Here is an example:
// x is a random number, or some key code from the user
if(!somespecific_keycode)
do the general stuff
else
do specific stuff
and the other solution
if(somespecific_keycode)
do the specific stuff
else
do general stuff
Efficient if-else StatementsWhile in a serial if block, all the conditions are tested, in an if-else block the remaining tests are skipped altogether once an if expression evaluates to true. This approach is known as a circuit-breaker behavior and is way more efficient than a serial if block.
else can be omitted for any if statement, there is nothing special in the last if of an if / else if chain. This is documented in any JavaScript grammar, e.g. in the specification.
An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.
The common rule is to put more likely case first, it's considered to be more readable.
Prefer to put them in the order that makes the code clearer, which is usually having the more likely to be executed first.
As others said: in terms of performance you should best rely on your compiler and your hardware (branch prediction, speculative execution) to do the right thing.
In case you are really concerned that these two don't help you enough, GCC provides a builtin (__builtin_expect) with which you can explicitly indicate the expected outcome of a branch.
In terms of code readability, I personally like the more likely case to be on top.
Unless you experience a performance problem, don't worry about it.
If you do experience a performance problem, try switching them around and measure which variant is faster, if any of them.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With