douluyezhen4512 2014-07-19 20:37
浏览 16
已采纳

循环切换或切换循环

I was wondering which code is effective. Notice, that $type = 1 is same during the whole loop.

if(!$handle = opendir('.')) {
    return false;
}

$result = array();
while(false !== ($entry = readdir($handle))) {
    if(!$resDir = self::getUrlByType($type, $entry)){
        continue;   
    }

    switch($type) {
        case 1:
            /* do something */
            break;

        case 2:
            /* do something different */
            break;
    }
}
closedir($handle);

I think, that these both codes should be proceesed with same duration, because it is only one condition there.

if(!$handle = opendir('.')) {
    return false;
}

switch($type) {
    case 1:
        $result = array();
        while(false !== ($entry = readdir($handle))) {
            if(!$resDir = self::getUrlByType($type, $entry)){
                continue;   
            }

            /* do something */
        }
        break;

    case 2:
        $result = array();
        while(false !== ($entry = readdir($handle))) {
            if(!$resDir = self::getUrlByType($type, $entry)){
                continue;   
            }

            /* do something different */
        }
        break;
}


closedir($handle);

I made negative microtime footprint at the begining of each script $time = -microtime(true); and the difference between current microtime $time += microtime(true); at the end of script. After i displayed the results echo "Time: ", sprintf('%f', $time), " "; i saw these values:

Time of first script was average between 0.0084 and 0.0203.

The secon results were much different, average between 0.0062 and 0.0072.

My question is, what is the case of this behaviour? Why didnt PHP compiler cashed that?

This ist the PHP output:

Type: 1
Type: 1
Type: 1
Type: 1
Type: 1
Type: 1
Type: 1
Type: 1
Time: 0.000103
Type: 1
Type: 1
Type: 1
Type: 1
Type: 1
Type: 1
Type: 1
Type: 1
Time: 0.000065
  • 写回答

1条回答 默认 最新

  • douqian1975 2014-07-19 20:41
    关注

    A loop inside a switch would be preferred, in my opinion. There can be a case where it may make more sense one way or the other so this depends on the scenario.

    But on a logistical stand point, having a loop inside of a switch means you only have to check for one condition and loop through a lot of "known" process. While if you loop a switch it constantly checks a state then does one process of known code just to repeat itself with a bit more overheard.

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

报告相同问题?

悬赏问题

  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 个人网站被恶意大量访问,怎么办
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大