Home > Backend Development > C++ > \'while (1) vs. for (;;): Does Compiler Optimization Eliminate Performance Differences?\'

\'while (1) vs. for (;;): Does Compiler Optimization Eliminate Performance Differences?\'

Mary-Kate Olsen
Release: 2024-10-31 22:18:29
Original
247 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template