最快/正确的if/else if语句排序方式


Fastest/Proper way of ordering if/else if statements

在PHP中,是否有最快/正确的方法来排序if/else if语句?出于某种原因,在我的脑海中,我喜欢认为第一个if语句应该是预期的"最受欢迎"的条件,其次是第二个,等等。但是,这真的重要吗?如果第二个条件是最常见的选择(意味着系统必须总是读取第一个条件),是否会影响速度或处理时间

,

if ("This is the most chosen condition" == $conditions)
{
}
else if ("This is the second most chosen condition" == $conditions)
{
}
else if ("This is the third most chosen condition" == $conditions)
{
}

速度方面,这不会有什么不同…不太明显……顺序是有意义的(把最常用的条件放在前面会更快),但是它没有多大意义。选择为修改和维护代码的人提供最佳可读性的顺序。他们以后会感谢你的。

编辑:另外,考虑一下:

函数返回的概率为25%。我更喜欢写:

if ( $chance25 )
    return;
else if ( $chance40 )
    doSomething();
else if ( $chance30 )
    doSomethingElse();
else if ( $chance5 )
    doSomethingElse2();

而不是:

if ( $chance40 )
    doSomething();
else if ( $chance30 )
    doSomethingElse();
else if ( $chance25 )
    return;
else if ( $chance5 )
    doSomethingElse2();

按功能排序会更好…

EDIT2:

一种尺寸不适合所有人。如果您的条件是返回布尔值的方法,则根据方法运行的速度和概率对它们排序。我想没有一个好的答案,你需要适应。例如,如果我的$chance25被一个方法reallySlowMethodDoNotUseUnlessYouReallyHaveTo()取代,我肯定会最后检查它。: D

我同意@Luchian的观点。您的主要关注点应该是代码的可读性

在优化代码之前,应该对应用程序进行分析。如何排序条件高度依赖于"每个条件"所花费的时间。

举个例子:

         Execution time - %ge called
Case 1 - 50 seconds (80% of time)
Case 2 - 10 seconds (15% of time)
Case 3 - 1 second    (5% of time)
100 runs:
Order A (In the order of "how often a condition is executed")
Case 1, Case 2, Case 3 = (80 * 50) + (15 * 60) + (5 * 61) = 5205 seconds
Order B (In the order of "execution times")
Case 3, Case 2, Case 1 = (5 * 1) + (15 * 11) + (80 * 61) = 5050 seconds

您的应用程序可能是一个web应用程序(因为这是PHP最流行的用法),所以大多数时候它等待外部资源,如数据库,文件访问或web服务。除非你是在一个执行了几千次的循环中,或者在一个递归方法中,哪个条件先出现并不重要。努力编写易于阅读的代码。

取决于您对操作的偏好

你可能想要激活条件二而不是条件一反之亦然

$value=25;
if ($value > 20)
{
$value=200;
}
else if ($value < 50)
{
$value=5;
}

如果您只是根据多个可能的文本值检查$conditions的值,而不是执行if/else,请使用switch。

switch ($conditions) {
    case "This is the most chosen condition":
        // do stuff
        break;
    case "This is the second most chosen condition":
        // do stuff
        break;
    case "This is the third most chosen condition":
        // do stuff
        break;
    default:
        // do stuff
}

如果最常见的情况是第一个,它将不需要评估任何其他情况,因此将更快,但差异将是如此之小,以至于这种方式或那种方式真的无关紧要。通常你应该更注重可读性而不是速度。