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
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.
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.
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.
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.
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.
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