Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest/Proper way of ordering if/else if statements

In PHP, is there a fastest/proper way of ordering if/else if statements? For some reason, in my head, I like to think that the first if statement should be the anticipated "most popular" met condition, followed by the 2nd, etc. But, does it really matter? Is there is a speed or processing time affected if the 2nd condition is the most popular choice (meaning the system must always read the first condition)

Ex:

if ("This is the most chosen condition" == $conditions)
{

}
else if ("This is the second most chosen condition" == $conditions)
{

}
else if ("This is the third most chosen condition" == $conditions)
{

}
like image 528
Luke Shaheen Avatar asked Dec 27 '22 14:12

Luke Shaheen


1 Answers

Speedwise, it won't make a difference... Not a noticeable one... The order does count (it's sensibly faster putting the most used condition first), however it doesn't count for much. Choose the order which provides the best readability to those modifying and maintaining your code. They'll thank you later.

EDIT: Also, consider this:

My function will return with a 25% chance. I prefer writing:

if ( $chance25 )
    return;
else if ( $chance40 )
    doSomething();
else if ( $chance30 )
    doSomethingElse();
else if ( $chance5 )
    doSomethingElse2();

rather than:

if ( $chance40 )
    doSomething();
else if ( $chance30 )
    doSomethingElse();
else if ( $chance25 )
    return;
else if ( $chance5 )
    doSomethingElse2();

It's just nicer ordering by functionality...

EDIT2:

One size does not fit all. If your conditions are methods returning booleans, order them by how fast the method runs combined with the chance. I guess there's not really one good answer, you need to adapt. For example, if my $chance25 was replaced by a method reallySlowMethodDoNotUseUnlessYouReallyHaveTo(), I would surely check it last. :D

like image 186
Luchian Grigore Avatar answered Dec 30 '22 03:12

Luchian Grigore