最快/正确的if/else语句排序方式 [英] Fastest/Proper way of ordering if/else if statements

查看:247
本文介绍了最快/正确的if/else语句排序方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP中,是否有一种最快/正确的if/else if语句排序方式?出于某种原因,在我的脑海中,我想认为第一个if语句应该是预期的最受欢迎"条件,然后是第二个,以此类推.但是,这真的重要吗?如果第二个条件是最受欢迎的选择,是否会影响速度或处理时间(这意味着系统必须始终读取第一个条件)

In PHP, is there a fastest/proper way of ordering if/else if statements? For some reason, in my head, I like to think that the first if statement should be the anticipated "most popular" met condition, followed by the 2nd, etc. But, does it really matter? Is there is a speed or processing time affected if the 2nd condition is the most popular choice (meaning the system must always read the first condition)

例如:

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

}

推荐答案

速度方面,不会有什么不同...不是很明显...订单确实很重要(将最常用的条件放在首位的速度明显更快) ),但它并没有多大用处.选择为那些修改和维护您的代码提供最佳可读性的顺序.他们待会儿会谢谢你.

Speedwise, it won't make a difference... Not a noticeable one... The order does count (it's sensibly faster putting the most used condition first), however it doesn't count for much. Choose the order which provides the best readability to those modifying and maintaining your code. They'll thank you later.

另外,请考虑以下问题:

Also, consider this:

我的函数将以25%的机会返回. 我更喜欢写:

My function will return with a 25% chance. I prefer writing:

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();

按功能排序更方便...

It's just nicer ordering by functionality...

一种尺寸并不适合所有尺寸.如果您的条件是返回布尔值的方法,请根据方法运行的快慢和机会来对它们进行排序.我猜确实没有一个很好的答案,您需要适应.例如,如果我的$ chance25被方法reallySlowMethodDoNotUseUnlessYouReallyHaveTo()代替,我肯定会最后检查它. :D

One size does not fit all. If your conditions are methods returning booleans, order them by how fast the method runs combined with the chance. I guess there's not really one good answer, you need to adapt. For example, if my $chance25 was replaced by a method reallySlowMethodDoNotUseUnlessYouReallyHaveTo(), I would surely check it last. :D

这篇关于最快/正确的if/else语句排序方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆