C语言中两种常用循环方式及对应汇编代码
(1) X86汇编
83: int sum = 0x10;
0040B8E8 mov dword ptr [ebp-4],10h
84: for ( int i = 0; i < sum; ++i )
0040B8EF mov dword ptr [ebp-8],0
0040B8F6 jmp main+31h (0040b901)
0040B8F8 mov eax,dword ptr [ebp-8]
0040B8FB add eax,1
0040B8FE mov dword ptr [ebp-8],eax
0040B901 mov ecx,dword ptr [ebp-8]
0040B904 cmp ecx,dword ptr [ebp-4]
0040B907 jge main+3Bh (0040b90b)
85: {
86: ;
87: }
0040B909 jmp main+28h (0040b8f8)
88:
89: for ( int j = sum; j > 0 ; --j )
0040B90B mov edx,dword ptr [ebp-4]
0040B90E mov dword ptr [ebp-0Ch],edx
0040B911 jmp main+4Ch (0040b91c)
0040B913 mov eax,dword ptr [ebp-0Ch]
0040B916 sub eax,1
0040B919 mov dword ptr [ebp-0Ch],eax
0040B91C cmp dword ptr [ebp-0Ch],0
0040B920 jle main+54h (0040b924)
90: {
91: ;
92: }
0040B922 jmp main+43h (0040b913)
93: }
方式1循环有7条指令; 方式2循环有6条指令。 因此效率差不多。
(2) AT&T汇编
movl $16, -4(%ebp) // int sum = 0x10;
----------------------------------方式1--------------------------------------
movl $0, -8(%ebp)
.L2:
movl -8(%ebp), %eax
cmpl -4(%ebp), %eax
jl .L4
jmp .L3
.L4:
leal -8(%ebp), %eax
incl (%eax)
jmp .L2
-----------------------------方式2----------------------------------------------
.L3:
movl -4(%ebp), %eax
movl %eax, -8(%ebp)
.L6:
cmpl $0, -8(%ebp)
jg .L8
jmp .L7
.L8:
leal -8(%ebp), %eax
decl (%eax)
jmp .L6
方式1循环有6条指令; 方式2循环有5条指令。 因此效率也差不多。
综上所述:2种方法效率差不多,但方式1(递增)更常用。