What is faster: many ifs, or else if?

ondrobaco picture ondrobaco · Nov 25, 2009 · Viewed 33k times · Source

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?

Answer

James B picture James B · Nov 25, 2009

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.