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:
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
GCC:
In GCC, both loops compile to the same assembly code, as shown below:
.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
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.
Descargo de responsabilidad: Todos los recursos proporcionados provienen en parte de Internet. Si existe alguna infracción de sus derechos de autor u otros derechos e intereses, explique los motivos detallados y proporcione pruebas de los derechos de autor o derechos e intereses y luego envíelos al correo electrónico: [email protected]. Lo manejaremos por usted lo antes posible.
Copyright© 2022 湘ICP备2022001581号-3