Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is faster: many ifs, or else if?

I'm iterating through an array and sorting it by values into days of the week.

In order to do it I'm using many if statements. Does it make any difference to the processing speed if I use many ifs, versus a set of else if statements?

like image 801
ondrobaco Avatar asked Nov 25 '09 10:11

ondrobaco


People also ask

What is better than multiple if statements?

Switch statement works better than multiple if statements when you are giving input directly without any condition checking in the statements. Switch statement works well when you want to increase the readability of the code and many alternative available.

Why use else if instead of multiple if?

Summary: By using an ELSE IF structure instead of multiple IF we can avoid “combined conditions” ( x<y && y<z ). Instead we can use a simplified condition (y<z). Furthermore ELSE IF is more efficient because the computer only has to check conditions until it finds a condition that returns the value TRUE.

Does if else affect performance?

In general it will not affect the performance but can cause unexpected behaviour. In terms of Clean Code unneserry if and if-else statements have to be removed for clarity, maintainability, better testing. One case where the performance will be reduced because of unnecessary if statements is in loops.

Is else if better than nested IF?

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.


1 Answers

Yes, use an else if, consider the following code:

if(predicateA){   //do Stuff } if(predicateB){   // do more stuff } 

of

if(predicateA){   // } else if(predicateB){   // } 

in the second case if predicateA is true, predicateB (and any further predicates) will not need to be evaluated (and so the whole code will execute faster), whereas in the first example if predicateA is true, predicateB will still always be evaluated, and you may also get some unexpected suprises if predicateA and predicateB are not mutually exclusive.

like image 185
James B Avatar answered Oct 05 '22 00:10

James B