while (1) vs. for (;;): Is There a Speed Difference?
Question:
Does using while (1) instead of for (;;) result in a performance difference in infinite loops?
Answer:
In most modern compilers, there is no performance difference between while (1) and for (;;).
Explanation:
Here's a technical analysis of how these loops are implemented in compilers:
Perl:
Both while (1) and for (;;) result in the same opcodes, as demonstrated by the perl -MO=Concise output:
<code class="shell">a <@> leave[1 ref] vKP/REFC ->(end) 1 <0> enter ->2 2 <;> nextstate(main 2 -e:1) v ->3 9 <2> leaveloop vK/2 ->a 3 <{> enterloop(next->8 last->9 redo->4) v ->4 - <@> lineseq vK ->9 4 <;> nextstate(main 1 -e:1) v ->5 7 <@> print vK ->8 5 <0> pushmark s ->6 6 <$> const[PV "foo\n"] s ->7 8 <0> unstack v ->4 -e syntax OK</code>
GCC:
In GCC, both loops compile to the same assembly code, as shown below:
<code class="assembly">.globl t_while t_while: .L2: movl $.LC0, %edi call puts jmp .L2 .globl t_for t_for: .L5: movl $.LC0, %edi call puts jmp .L5</code>
Therefore, in most cases, there is no need to prefer one over the other based on performance concerns. The choice can be based on code readability or other factors.
The above is the detailed content of \'while (1) vs. for (;;): Does Compiler Optimization Eliminate Performance Differences?\'. For more information, please follow other related articles on the PHP Chinese website!