Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if statement condition optimisation

I have an if statement with two conditions (separated by an OR operator), one of the conditions covers +70% of situations and takes far less time to process/execute than the second condition, so in the interests of speed I only want the second condition to be processed if the first condition evaluates to false.

if I order the conditions so that the first condition (the quicker one) appears in the if statement first - on the occasions where this condition is met and evaluates true is the second condition even processed?

if ( (condition1) | (condition2) ){
  // do this
}

or would I need to nest two if statements to only check the second condition if the first evaluates to false?

if (condition1){
  // do this
}else if (condition2){
  // do this
}

I am working in PHP, however, I assume that this may be language-agnostic.

like image 224
JimmyJ Avatar asked Aug 29 '08 18:08

JimmyJ


1 Answers

For C, C++, C#, Java and other .NET languages boolean expressions are optimised so that as soon as enough is known nothing else is evaluated.

An old trick for doing obfuscated code was to use this to create if statements, such as:

a || b();

if "a" is true, "b()" would never be evaluated, so we can rewrite it into:

if(!a)
    b();

and similarly:

a && b();

would become

if(a)
    b();

Please note that this is only valid for the || and && operator. The two operators | and & is bitwise or, and and, respectively, and are therefore not "optimised".

EDIT: As mentioned by others, trying to optimise code using short circuit logic is very rarely well spent time.

First go for clarity, both because it is easier to read and understand. Also, if you try to be too clever a simple reordering of the terms could lead to wildly different behaviour without any apparent reason.

Second, go for optimisation, but only after timing and profiling. Way too many developer do premature optimisation without profiling. Most of the time it's completely useless.

like image 71
Mats Fredriksson Avatar answered Oct 02 '22 21:10

Mats Fredriksson