1. 程式人生 > >do...while, while, for迴圈效率PK

do...while, while, for迴圈效率PK

debug版本:

do

{

sum++;

01321471 mov eax,dword ptr [sum]

01321474 add eax,1

01321477 mov dword ptr [sum],eax

} while (sum < a);

0132147A mov eax,dword ptr [sum]

0132147D cmp eax,dword ptr [a]

01321480 jl main+51h (01321471h)

 

do_begin

執行迴圈體

;影響標記位的指令

jxx do_begin

 

while (sum < a)

00BF1471 mov eax,dword ptr [sum]

00BF1474 cmp eax,dword ptr [a]

00BF1477 jge main+64h (0BF1484h)

{

sum++;

00BF1479 mov eax,dword ptr [sum]

00BF147C add eax,1

00BF147F mov dword ptr [sum],eax

}

00BF1482 jmp main+51h (0BF1471h)

while_begin

;jxx 影響標誌位的指令

執行迴圈體

jmp while_begin

while_end

 

for (int sum = 0; sum < a; sum++)

//計數器初始化

0039146A mov dword ptr [ebp-18h],0

//步長

00391471 jmp main+5Ch (039147Ch)

00391473 mov eax,dword ptr [ebp-18h]

00391476 add eax,1

00391479 mov dword ptr [ebp-18h],eax

//判斷執行條件

0039147C mov eax,dword ptr [ebp-18h]

0039147F cmp eax,dword ptr [a]

00391482 jge main+7Dh (039149Dh)

//執行迴圈體

{

printf("hehhe");

00391484 mov esi,esp

00391486 push 39585Ch

0039148B call dword ptr ds:[399114h]

00391491 add esp,4

00391494 cmp esi,esp

00391496 call __RTC_CheckEsp (0391140h)

}

0039149B jmp main+53h (0391473h)

 

從中可以看出debug版本do...while的效率要比while的效率高,而while的效率要比for迴圈高

 

編譯器在進行優化時,是將while迴圈和for迴圈轉化為do...while迴圈

while迴圈的優化

if(XXX)

{

do

{

do something

}while(XXX)

}

for迴圈的優化

for(int i = 0; XXX; ++I)

{

do something

}

 

int i = 0;

while(XXX)

{

do something

++i

}

 

 

int i = 0

if(XXX)

{

do

{

do something

++i

}while(XXX);

}