php 什么更快:多个if,否则if?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1796100/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What is faster: many ifs, or else if?
提问by ondrobaco
I'm iterating through an array and sorting it by values into days of the week.
我正在遍历一个数组并按值将其排序为一周中的几天。
In order to do it I'm using many ifstatements. Does it make any difference to the processing speed if I use many ifs, versus a set of else ifstatements?
为了做到这一点,我使用了许多if语句。如果我使用许多ifs 与一组else if语句,对处理速度有什么影响吗?
回答by James B
Yes, use an else if, consider the following code:
是的,使用 else if,请考虑以下代码:
if(predicateA){
//do Stuff
}
if(predicateB){
// do more stuff
}
of
的
if(predicateA){
//
}
else if(predicateB){
//
}
in the second case if predicateA is true, predicateB (and any further predicates) will not need to be evaluated (and so the whole code will execute faster), whereas in the first example if predicateA is true, predicateB will still always be evaluated, and you may also get some unexpected suprises if predicateA and predicateB are not mutually exclusive.
在第二种情况下,如果 predicateA 为真,则不需要计算 predicateB(以及任何进一步的 predicates)(因此整个代码将执行得更快),而在第一个示例中,如果 predicateA 为真,predicateB 仍将始终进行计算,如果 predicateA 和 predicateB 不是互斥的,你也可能会得到一些意想不到的惊喜。
回答by duffymo
I doubt that a micro optimization like this will make a measurable difference in your code.
我怀疑像这样的微优化会对您的代码产生显着的影响。
Your sorting algorithm is more likely to be the source of a performance problem. Which sorting algorithm you choose will be critical, not many "ifs" versus "else if".
您的排序算法更有可能是性能问题的根源。您选择哪种排序算法将是至关重要的,“ifs”与“else if”并不多。
UPDATE:
更新:
The points made by others about "else if" being a better choice, due to its early exit and exclusive logic characteristics, suggest that it should be preferred over "if" in this case.
其他人提出的关于“else if”是更好选择的观点,由于它的提前退出和独占逻辑特性,表明在这种情况下它应该比“if”更受欢迎。
But the point about algorithm choice still stands - unless your data set is very small.
但是关于算法选择的观点仍然存在——除非你的数据集非常小。
It's obvious that O(log n) would be better than O(n^2), but size of dataset matters as well. If you have only a few elements, you might not notice the difference. In that case, coding an inefficient method in the cleanest, most readable, most easily understandable at a glance could be your best bet.
很明显,O(log n) 会比 O(n^2) 好,但数据集的大小也很重要。如果您只有几个元素,您可能不会注意到其中的差异。在这种情况下,以最简洁、最易读、最容易理解的方式编写一种低效的方法可能是您最好的选择。
回答by Roch
回答by James
To be honest I don't think it would matter which way you do it in terms of performance, I doubt you would see any difference. I would recommend using a switch statement which isn't a performance enhancment, simply syntactically nicer:
老实说,我认为在性能方面采用哪种方式并不重要,我怀疑您会看到任何区别。我建议使用不是性能增强的 switch 语句,只是在语法上更好:
switch ($day)
{
case "Monday":
// do something with Monday
break;
case "Tuesday":
// do something with Tuesday
break;
case "Wednesday":
// do something with Wednesday
break;
}
回答by Laurent
I made a benchmark if there's a true difference between successive if() and if() then a few elseif()
如果连续的 if() 和 if() 然后几个 elseif() 之间有真正的区别,我做了一个基准测试
I put a big string and did about 20 strpos() each time (x100 000) with the two methods and it showed this result :
我放了一个大字符串,每次(x100 000)用这两种方法做了大约 20 个 strpos() ,它显示了这个结果:
Try 1 : 0.5094 (including elseif)
Try 2 : 0.6700 (including only if)
There's no doubt. I already knew sucessive elseif() were faster, even though there's a return in the middle ; it's still good to put some statistics in the answer.
毫无疑问。我已经知道连续 elseif() 更快,即使中间有一个返回;在答案中加入一些统计数据仍然很好。
回答by Yannick Motton
else ifwould be faster in the sense that you compare until you hit a condition that resolves to true, and you skip the rest of the ifs.
else if在比较的意义上会更快,直到遇到解析为 true 的条件,然后跳过ifs的其余部分。
Also consider reordering the compares in order of descending frequency.
还可以考虑按频率降序对比较重新排序。
And using the switchstatement depending on the datatype of the object you are comparing.
并switch根据您要比较的对象的数据类型使用该语句。
However at this point, as duffymo has suggested, you would be micro optimizing. The performance gain will never be as significant if you haven't chosen the right sorting algorithm for the job first.
然而,此时,正如 duffymo 所建议的,您将进行微优化。如果您没有先为作业选择正确的排序算法,则性能提升将永远不会如此显着。
回答by PP.
If the values are integers you may achieve an optimisation by using a table lookup. E.g. say you have 256 values that map into 7 days somehow, you could set up an array with 256 cells and each cell contained the day of week you wanted. Then instead of:
如果值是整数,您可以通过使用表查找来实现优化。例如,假设您有 256 个值以某种方式映射到 7 天,您可以设置一个包含 256 个单元格的数组,每个单元格包含您想要的星期几。然后而不是:
if ( value == 0 ) {
dayofweek = 1;
} else if ( value == 1 ) {
dayofweek = 2;
} else if ( value == 2 ) {
dayofweek = 3;
} else if ...
.. you could have..
.. 你可以有..
dayofweek = lookuparray[value];
Of course, if you use this technique, then you should check the bounds of value first.
当然,如果你使用这种技术,那么你应该首先检查值的边界。
回答by Martin Bean
I would put another vote in for opting for a switch() statement instead.
我会再次投票选择 switch() 语句。
回答by MaxVT
In general, "else if" style can be faster because in the series of ifs, every condition is checked one after the other; in an "else if" chain, once one condition is matched, the rest are bypassed.
一般来说,“else if”样式会更快,因为在一系列 if 中,每个条件都一个接一个地检查;在“else if”链中,一旦匹配一个条件,其余的将被绕过。
The fastest would be a table dispatch, which is what a switch statement gets optimized into when there are enough cases in it (if there are few cases in a switch, it gets translated into a series of if-else checks in the resulting machine code).
最快的是表调度,这是当 switch 语句中有足够多的 case 时被优化成的(如果 switch 中的 case 很少,它会在结果机器代码中转换为一系列 if-else 检查)。
回答by Oliver Friedrich
The decision to use many if-statements or one if-elseif-elseif... should not rely on performance, since this decision involves the program flow massively.
使用多个 if 语句或一个 if-elseif-elseif 的决定不应依赖于性能,因为该决定大量涉及程序流程。
I doubt that you can switch from many if-statements to a big if-elseif without loosing functionality.
我怀疑您是否可以在不丢失功能的情况下从多个 if 语句切换到一个大的 if-elseif。
Its a design question, not a perfomance one.
它是一个设计问题,而不是一个性能问题。


