If the optimization of the operator condition

I have an if statement with two conditions (separated by an OR operator), one of the conditions covers + 70% of situations and takes much less time to process / execute than the second condition, so in the interest of speed I want only the second condition for processing if the first the condition is evaluated as false.

if I arrange the conditions so that the first condition (faster) appears in the if statement first - in cases where this condition is satisfied and evaluated as true, will the second condition be processed at all?

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

or would I need to nest two if statements to check only the second condition, if the first is evaluated as false?

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

I work in PHP, however I assume that this may not be language dependent.

+5
11

C, ++, #, Java .NET- , , , .

, if, :

a || b();

"a" , "b()" , :

if(!a)
    b();

:

a && b();

if(a)
    b();

, || && . | , , , "".

EDIT: , .

, . , , - .

-, , . . .

+9

C, ++ Java :


if (condition1 | condition2) {
  ...
}

, .

:


if (condition1 || condition2) {
  ...
}

condition2, condition1 - false. , 2 .

|| if/else.

+3

- n- .

, :

  • 2
  • - , , 3us.

" " . , , , ( ) , .

- ( , !) , , .

, .

+2

PHP , , , . ( ):

<?php
/* ch06ex07 โ€“ shows no output because of short circuit evaluation */

if (true || $intVal = 5) // short circuits after true
{

echo $intVal; // will be empty because the assignment never took place
}

?>
+2

. - , , . :

if (i < array.size() && array[i]==foo) ...

, [i] , . , , , !

, , .

+2

, , , . ( ++) :

if( pObj != NULL && *pObj == "username" ) {
    // Do something...
}

, , pObj . , if.

+1

, . Perl, , , PHP. , .

0

.

0

| - PHP. $a OR $b. . , , PHP . , && false, PHP .

0

VB.net "OrElse" "AndAlso"

OrElse , .

If FirstName = "Luke" OrElse FirstName = "Darth" Then
   Console.Writeline "Greetings Exalted One!"
End If

AndAlso , False- .

If FirstName = "Luke" AndAlso LastName = "Skywalker" Then
   Console.Writeline "You are the one and only."
End If

.

0

All Articles