Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If and else, were should I put the more likely part?

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
like image 841
Bartlomiej Lewandowski Avatar asked Aug 01 '12 16:08

Bartlomiej Lewandowski


People also ask

How do you use if else effectively?

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.

Is it necessary to add else after ELSE IF?

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.

What is the ELSE statement followed by?

An if statement can be followed by an optional else statement, which executes when the Boolean expression is false.


4 Answers

The common rule is to put more likely case first, it's considered to be more readable.

like image 145
Danil Speransky Avatar answered Nov 10 '22 04:11

Danil Speransky


Prefer to put them in the order that makes the code clearer, which is usually having the more likely to be executed first.

like image 39
pb2q Avatar answered Nov 10 '22 05:11

pb2q


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.

like image 20
BjoernD Avatar answered Nov 10 '22 05:11

BjoernD


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.

like image 28
Sebastian Paaske Tørholm Avatar answered Nov 10 '22 06:11

Sebastian Paaske Tørholm