Which loop is faster in C: while or for?

10

Being a loop while and a for that rotate 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();
}
    
asked by anonymous 10.12.2015 / 19:00

3 answers

10

Most compilers will produce identical codes and there will be no difference, but only testing on the specific version of a compiler to know. Here's the hint to do and find out for yourself.

Code example 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>

Code example 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>

Font .

That is, the result is the same in this case.

    
10.12.2015 / 19:10
3

The differences - to be - are not significant, even for a large number of data. The choice between one structure and another is more about a programmer style and / or readability of the code than about performance issues. The most practical way to gauge the performance gap is by always timing the execution and doing a simple statistical analysis. If anyone considers it important, I can do this and add to this answer.

    
10.12.2015 / 19:30
-2
There is virtually no difference. However, While looks for True or False . Already For it has to do a comparison with values. While ends up being "faster".

    
10.12.2015 / 19:06