优化大量IF语句

时间:2011-09-12 15:32:55

标签: php if-statement nested-if

我有一大堆嵌套的IF语句,我想知道如果有人对如何优化速度,大小和可读性有任何建议。

下面是一个if语句及其'嵌套语句的示例。文件中大约有25-30个。

if( $row["inlet_moisture"] > $row["inlet_moisture_high_warning"] ) {
    if( $row["inlet_moisture"] > $row["inlet_moisture_high_critical"] ) {
        if( $row["inlet_high_critical"] == 0 ) {
            if( $row["email_notification"] == 1 ) {

            }
            if( $row["mobile_notification"] == 1 ) {

            }
        }
    } else {
        if( $row["inlet_high_warning"] == 0 ) {
            if( $row["email_notification"] == 1 ) {

            }
            if( $row["mobile_notification"] == 1 ) {

            }
        }
    }
} else if( $row["inlet_moisture"] < $row["inlet_moisture_low_warning"] ) {
    if( $row["inlet_moisture"] < $row["inlet_moisture_low_critical"] ) {
        if( $row["inlet_low_critical"] == 0 ) {
            if( $row["email_notification"] == 1 ) {

            }
            if( $row["mobile_notification"] == 1 ) {

            }
        }
    } else {
        if( $row["inlet_low_warning"] == 0 ) {
            if( $row["email_notification"] == 1 ) {

            }
            if( $row["mobile_notification"] == 1 ) {

            }
        }
    }
}

这个想法是;我有一个读数(温度/速度/湿度),我需要检查它是否达到任何限制(高警告/高关键/低警告/低关键),如果是我首先需要检查我是否已发出警报。如果没有发送警报,我需要检查用户是否已请求警报通知(手机/电子邮件/两者)

目前这有效。我只是不喜欢它有多重?我能改进吗?

感谢。

2 个答案:

答案 0 :(得分:2)

Premature optimisation is the root of all evil - 我们在这里处理的是什么,无论你做什么,都不会对绩效产生太大/任何明显的影响。

话虽如此,大量if语句通常可以替换为一个或多个switch结构,但这是否会提高性能可读性是值得商榷的。您也可以为重复的代码位创建一些函数,尽管这实际上可能会对性能产生负面影响。

从上面的评论中...创建名称更好的变量对性能的影响几乎为零。如果稍微增加你的内存使用量,但处理时间的影响将接近于零。并且,如果您将值评估为布尔值,则不需要将它们明确地转换为布尔值,因为1仍然评估为TRUE,0评估为FALSE。但是,如果你想这样做

$email_notification = $row["email_notification"] == 1 ? true : false;

......不必要地长篇大论,你可以这样做:

$email_notification = $row["email_notification"] == 1;

...或...

$email_notification = (bool) $row["email_notification"];

......它会产生同样的效果。

答案 1 :(得分:2)

这在我看来更清楚,即使你可以结合嵌套的ifs我更喜欢这个

if( $row["inlet_moisture"] > $row["inlet_moisture_high_critical"] ) {
  if( $row["inlet_high_critical"] == 0 ) {
   $message = 'the pertinent message';
  }
}
else if( $row["inlet_moisture"] > $row["inlet_moisture_high_warning"] ) {
  if( $row["inlet_high_warning"] == 0 ) {
   $message = 'the pertinent message';
  }
}
else if( $row["inlet_moisture"] < $row["inlet_moisture_low_critical"] ) {
  if( $row["inlet_low_critical"] == 0 ) {
   $message = 'the pertinent message';
  }
}
else if( $row["inlet_moisture"] < $row["inlet_moisture_low_warning"] ) {
  if( $row["inlet_low_warning"] == 0 ) {
   $message = 'the pertinent message';
  }
}


if( $row["email_notification"] == 1 ) {
  sendMessage($message, $email);
}
if( $row["mobile_notification"] == 1 ) {
  sendMessage($message, $mobile);    
}
相关问题