Which loop is faster in C: while or for?

Asked

Viewed 2,257 times

10

Being a bond while and a for that run the same number of times, which is faster? Example:

while:

int i = 0;
int max = 10;
while(i<max){
    funcao();
    i++;
}

for:

int i;
int max = 10;
for(i=0; i<max; i++){
    funcao();
}
  • 1

    the for allows, since C99, to compartmentalize more the control variable: for (int i = 0; i < max; i++) { /* whatever */ }

  • And remember that C11 is already the standard in GCC.

3 answers

12


Most compilers will produce identical code and there will be no difference, but only testing in the specific version of a compiler to know. It is suggested to do and discover on your own.

Example of code generated for for:

40047f:   c7 45 f4 00 00 00 00    movl   $0x0,-0xc(%rbp)
400486:   eb 0a                   jmp    400492 <main+0x1e>
400488:   8b 45 f4                mov    -0xc(%rbp),%eax
40048b:   01 45 fc                add    %eax,-0x4(%rbp)
40048e:   83 45 f4 01             addl   $0x1,-0xc(%rbp)
400492:   83 7d f4 09             cmpl   $0x9,-0xc(%rbp)
400496:   7e f0                   jle    400488 <main+0x14>

Example of code generated for while:

400498:   c7 45 f8 00 00 00 00    movl   $0x0,-0x8(%rbp)
40049f:   eb 0a                   jmp    4004ab <main+0x37>
4004a1:   8b 45 f8                mov    -0x8(%rbp),%eax
4004a4:   01 45 fc                add    %eax,-0x4(%rbp)
4004a7:   83 45 f8 01             addl   $0x1,-0x8(%rbp)
4004ab:   83 7d f8 09             cmpl   $0x9,-0x8(%rbp)
4004af:   7e f0                   jle    4004a1 <main+0x2d>

Source.

That is, the result is the same in this case presented using the same compiler.

3

The differences - if any - are not significant, even for a large number of data. The choice between one structure and another relates more to the programmer’s style and/or readability of the code than to performance issues. The most practical way of measuring the difference in performance always ends up timing the execution and making a simple statistical analysis. If anyone considers it important, I can do that and add to this answer.

-2

The statement itself already says that both run the same number of times... That is, the complexity of these algorithms will be equal. O(n 2).

  • 3

    The question is which is the fastest, not which is the most complex. Speed and complexity can complement each other in an analysis, but they are completely different things

  • 2

    And the complexity of both is O(N) and not O(N 2).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.