订购if/else if语句的最快/最合适的方式

Luk*_*een 4 php benchmarking

在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)
{

}
Run Code Online (Sandbox Code Playgroud)

Luc*_*ore 6

速度方面,它不会有所作为......不是一个明显的...订单确实计数(将最常用的条件放在第一位的速度明显更快),但它并不重要.选择为修改和维护代码提供最佳可读性的顺序.他们以后会感谢你的.

编辑:另外,考虑这个:

我的功能将以25%的几率返回.我更喜欢写作:

if ( $chance25 )
    return;
else if ( $chance40 )
    doSomething();
else if ( $chance30 )
    doSomethingElse();
else if ( $chance5 )
    doSomethingElse2();
Run Code Online (Sandbox Code Playgroud)

而不是:

if ( $chance40 )
    doSomething();
else if ( $chance30 )
    doSomethingElse();
else if ( $chance25 )
    return;
else if ( $chance5 )
    doSomethingElse2();
Run Code Online (Sandbox Code Playgroud)

它的功能更好......

EDIT2:

一种尺寸并不适合所有人.如果您的条件是返回布尔值的方法,请根据方法运行的速度和机会来命令它们.我想这不是一个好的答案,你需要适应.例如,如果我的$ chance25被一个方法替换reallySlowMethodDoNotUseUnlessYouReallyHaveTo(),我肯定会检查它.:d