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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3