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.

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

报告相同问题?

悬赏问题

  • ¥15 对于这个问题的解释说明
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备