Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

If Else vs && ||

Is there a difference between coding with if else or && and || operators.

For example in if-else style I can write this code

for( var i = 0; i < 1000000000; i ++ ) {
    if( i % 2 == 0 ) {
        f1();
    } else {
        f2();
    }
}

And in && and || style I can get same result with this code

(( i % 2 == 0 ) && (test1() || true)) || test2();

I tested them in JS, they are working approx on same time, but I didnt test them on C++. Maybe it depends compiler or language.

Is there a speed difference? Or any difference at all?

Thank you

like image 260
Gor Avatar asked Nov 20 '15 15:11

Gor


People also ask

What is better than if else?

A switch statement is usually more efficient than a set of nested ifs. Deciding whether to use if-then-else statements or a switch statement is based on readability and the expression that the statement is testing.

What is else if vs else?

Use else to specify a block of code to be executed, if the same condition is false. Use else if to specify a new condition to test, if the first condition is false. Use switch to specify many alternative blocks of code to be executed.

What is faster than if else?

A switch statement is significantly faster than an if-else ladder if there are many nested if-else's involved. This is due to the creation of a jump table for switch during compilation. As a result, instead of checking which case is satisfied throughout execution, it just decides which case must be completed.

Which is better if or else if?

In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.


1 Answers

It may work the same, but one thing you may want to consider is readability. The first instance of your code is very readable while the second one makes me want to grab a pen and paper and do the math. Speed and readability are trade-offs and unless your program is severely bottle-necked performance-wise, being readable is the better goal.

like image 62
Lawrence Aiello Avatar answered Sep 21 '22 15:09

Lawrence Aiello