do-while is the fastest loop in php?
- 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
The
do while
loop only has one jump statement (JMPNZ
), whereas thewhile
loop needs two (JMPZ
,JMP
). Thefor
loop needs three jump statements (JMPZNZ
,JMP
,JMP
) and has generally more complex logic.