do-while是php中最快的循环吗? [英] do-while is the fastest loop in php?
问题描述
我已经用简单的方法分析了 for , while 和 do-while 循环:
I have profiled for, while and do-while loops with something simple:
while ($var < 1000000) {
++$var;
}
do {
++$var;
} while ($var < 1000000);
for ($var = 0; $var < 1000000; ++$var) {
//do nothing
}
通过比较循环前后的microtime()。
by comparing microtime() before and after the loops.
do-while循环在很大程度上是最快的循环。 do-while 实际上比 while 快近一半。我知道它们有不同的用途( while 在循环执行之前检查条件,而 do-while 至少执行一次)。
The do-while loop is by a considerable amount the fastest loop. do-while is actually faster than while by almost half. I know that they are for different purposes ( while checks the condition before the loop executes and do-while executes at least once ).
我知道普遍的共识是,虽然不赞成使用循环,而做循环则更是如此。
I know the general consensus is that while loops are frowned upon and do-while even more so.
我的问题是为什么?考虑到PHP应用程序中使用了多少个for循环,不应该更多地使用 do-while 吗?即使使用 if 语句在循环执行之前检查条件,其性能提升还是相当可观的。
My question is why? Considering how many for loops are used in PHP applications, shouldn't do-while be used more? Even with an if statement to check a condition before the loop executes, the performance boost is considerable.
我目前接受的答案是代码易读是可疑的。
My currently accepted answer is that code legibility is the suspect.
推荐答案
- 微观优化是邪恶的 。它们会降低可读性,从而导致 否 可衡量的性能提升。即使您的应用程序确实具有数百万个迭代器的循环(我对此表示怀疑),差异仍然可以忽略不计。
-
while
之间的差异/做而
小于您说的话: http://codepad.viper- 7.com/M8cgt9 -
要了解为什么
做而
快一点的原因,请查看生成的操作码:
- Micro optimizations are evil. They reduce readability for no measurable performance gain. Even if your application does have loops with millions of iterators (which I doubt) the difference is still negligible.
- The difference between
while
/do while
is smaller than you say: http://codepad.viper-7.com/M8cgt9 To understand why
do while
is marginally faster, look at the generated opcodes:
line # * op fetch ext return operands
---------------------------------------------------------------------------------
# while loop
3 0 > ASSIGN !0, 0
4 1 > IS_SMALLER ~1 !0, 1000000
2 > JMPZ ~1, ->5
3 > PRE_INC !0
4 > JMP ->1
5 > > RETURN 1
# do while loop
3 0 > ASSIGN !0, 0
4 1 > PRE_INC !0
2 IS_SMALLER ~2 !0, 1000000
3 > JMPNZ ~2, ->1
4 > > RETURN 1
# for loop
3 0 > ASSIGN !0, 0
1 > IS_SMALLER ~1 !0, 1000000
2 > JMPZNZ 5 ~1, ->6
3 > PRE_INC !0
4 > JMP ->1
5 > > JMP ->3
6 > > RETURN 1
do while
循环仅具有一个跳转语句( JMPNZ
),而 while
循环则需要两个( JMPZ
, JMP
)。 for
循环需要三个跳转语句( JMPZNZ
, JMP
, JMP
),并且逻辑通常更复杂。
The do while
loop only has one jump statement (JMPNZ
), whereas the while
loop needs two (JMPZ
, JMP
). The for
loop needs three jump statements (JMPZNZ
, JMP
, JMP
) and has generally more complex logic.
这篇关于do-while是php中最快的循环吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!