哪个更快:很多 if,还是 else if?
我正在迭代一个数组,并按值将其排序为一周中的几天。
为了做到这一点,我使用了许多 if
语句。如果我使用许多 if
与一组 else if
语句,对处理速度有什么影响吗?
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 if
statements. Does it make any difference to the processing speed if I use many if
s, versus a set of else if
statements?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(11)
是的,使用 else if,请考虑以下代码:
of
在第二种情况下,如果 predicateA 为 true,则不需要评估 predicateB (以及任何其他谓词)(因此整个代码将执行得更快),而在第一种情况下例如,如果 predicateA 为 true,predicateB 仍将始终被求值,如果 predicateA 和 predicateB 不互斥,您也可能会得到一些意想不到的惊喜。
Yes, use an else if, consider the following code:
of
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.
我怀疑像这样的微观优化会给您的代码带来可衡量的差异。
您的排序算法更有可能是性能问题的根源。您选择哪种排序算法至关重要,而不是太多“if”与“else if”。
更新:
其他人提出的关于“else if”是更好选择的观点,由于其早期退出和排他性逻辑特征,表明在这种情况下应该优先于“if”。
但关于算法选择的观点仍然成立——除非你的数据集非常小。
显然 O(log n) 会比 O(n^2) 更好,但数据集的大小也很重要。如果您只有几个元素,您可能不会注意到其中的差异。在这种情况下,以最干净、最易读、最容易一目了然的方式编写低效方法可能是您的最佳选择。
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".
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.
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.
你可以看看 phpbench
但说实话如果你想在这个级别进行优化,你可能想学习除了 php 之外的其他东西。
You can have a look at phpbench
But to be honest if you want to optimize at this level, you might want to learn something else than php.
老实说,我认为在性能方面采用哪种方式并不重要,我怀疑您会看到任何差异。我建议使用 switch 语句,这不是性能增强,只是语法上更好:
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:
我做了一个基准,如果连续的 if() 和 if() 之间存在真正的区别,然后是一些 elseif()
我放了一个大字符串,并使用这两种方法每次(x100 000)执行大约 20 strpos() ,它显示了这一点结果:
毫无疑问。我已经知道连续的 elseif() 速度更快,即使中间有一个 return ;在答案中加入一些统计数据还是很好的。
I made a benchmark if there's a true difference between successive if() and if() then a few elseif()
I put a big string and did about 20 strpos() each time (x100 000) with the two methods and it showed this result :
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.
从某种意义上说,
else if
会更快,直到遇到解析为 true 的条件为止,然后跳过其余的if
。还可以考虑按频率降序对比较进行重新排序。
并根据要比较的对象的数据类型使用
switch
语句。然而,在这一点上,正如达菲莫所建议的,您将进行微观优化。如果您没有首先为作业选择正确的排序算法,那么性能提升将永远不会那么显着。
else if
would be faster in the sense that you compare until you hit a condition that resolves to true, and you skip the rest of theif
s.Also consider reordering the compares in order of descending frequency.
And using the
switch
statement depending on the datatype of the object you are comparing.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.
如果值是整数,您可以通过使用表查找来实现优化。例如,假设您有 256 个值以某种方式映射到 7 天,您可以设置一个包含 256 个单元格的数组,每个单元格包含您想要的星期几。然后,而不是:
.. 你可以有..
当然,如果你使用这种技术,那么你应该首先检查值的界限。
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:
.. you could have..
Of course, if you use this technique, then you should check the bounds of value first.
我会再次投票选择 switch() 语句。
I would put another vote in for opting for a switch() statement instead.
当 if 块返回从而完成该方法时,这个问题特别有趣。它也直接适用于 Java 中比较器的工作方式。
因此,我已运行每种方法(如下) 250.000.000 次,结果如下:
虽然最坏的情况比最好的情况花费 1.4 倍的时间,但请注意这是迭代的总和这些方法中的每一种都被执行了 2.5 亿次。假设人类需要 100 毫秒才能感知延迟,并且最差/更好的差异为 2.58 毫秒,这意味着您需要近一万亿(1000 * 1000 百万)次迭代才能感知不同方法之间的差异。
总结:使用
if-else
这是最快的选项之一,也是更易读且不易出错的选项。This question is specially interesting when the
if
block returns thus finishing the method. It also applies directly to the way comparators in Java work.I've thus run each method (bellow) 250.000.000 times and the results are as follows:
While the worst case takes 1.4 times longer than the best one do notice that this is the aggregate sum of iterating each one of these methods 250 million times. Assuming that it would take 100ms for a human to perceive delay and that the worst/better difference is 2.58 millis it would imply that you would need almost a trillion (1000 * 1000 millions) iterations to perceive the difference between different methods.
Summing it up: use
if-else
it's one of those cases where the fastest option is also the one with more legibility and less error-prone.一般来说,“else if”样式可以更快,因为在一系列 if 中,每个条件都会被一个接一个地检查;在“else if”链中,一旦满足一个条件,其余条件就会被绕过。
最快的是表调度,当 switch 语句中有足够的情况时,它会被优化成这样(如果 switch 中的情况很少,它会在生成的机器代码中转换为一系列 if-else 检查) )。
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.
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).
使用许多 if 语句或一个 if-elseif-elseif... 的决定不应该依赖于性能,因为这一决定涉及大量的程序流程。
我怀疑您是否可以从许多 if-语句切换到一个大的 if-elseif 而不会失去功能。
这是一个设计问题,而不是性能问题。
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.
I doubt that you can switch from many if-statements to a big if-elseif without loosing functionality.
Its a design question, not a perfomance one.