PHP的性能最差情况if else声明[关闭]

function quadrant($x,$y) {

if( $x >= 0 && $y >= 0 )
    $result = "point ($x,$y) lies in the First quandrant";
else if( $x < 0 && $y >= 0)
    $result = "point ($x,$y) lies in the Second quandrant";
else if( $x < 0 && $y < 0)
    $result = "point ($x,$y) lies in the Third quandrant";
else if( $x >= 0 && $y < 0)
    $result = "point ($x,$y) lies in the Fourth quandrant";

return $result;

}

$x=1;
$y=1;
$q = quadrant($x,$y);

what is the value of $x or $y that is the worst case in terms of performance? and how many comparisons are made?

what is the value of $x or $y that is the best case in terms of performance? and how many comparisons are made?

This is simply a matter of counting.

Best case: x and y both non-negative. 2 comparisons ($x >= 0 and $y >= 0).

Worst case: x non-negative and y negative. 6 comparisons. That's because php stops at the && if the first statement is already false since the result can't possibly be true no matter what the second statement returns. Thus, the second and third if will already stop evaluating after $x<0 is evaluated to false.
Also, the last if is totally unnecessary and just adds 2 comparisons in the "worst" case. Removing it and leaving just the else will get this case down to 4 and make "x and y both negative" the worst case with 5 comparisons.

Here's a more efficient version:

function quadrant($x,$y) {

    if( $x >= 0 ) {
        if( $y >= 0)
            return "point ($x,$y) lies in the First quandrant";
        else
            return "point ($x,$y) lies in the Fourth quandrant";
    }
    else if( $y >= 0)
        return "point ($x,$y) lies in the Second quandrant";
    else
        return "point ($x,$y) lies in the Third quandrant";

}

This has always 2 comparisons.