dongpai2468 2014-02-03 14:26
浏览 59
已采纳

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?

  • 写回答

1条回答 默认 最新

  • duannao3402 2014-02-03 14:29
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等