编译器VC++6.0有两种优化方案 O1(占用空间最小)和O2(运行效率最快) Debug下,编译器的优化能力是有限的,需要增加一些调试代码。Release版本下,编译器采用O2方案
15+20;
int nVarOne = 0;
int nVarTwo = 0;
nVarOne = nVarOne+1;
nVarOne = 1+2;
nVarOne = nVarOne+nVarTwo;
printf("nVarOne = %d\r\n", nVarOne);
return 0;
push offset aNvaroneD ; "nVarOne = %d\r\n"
call sub_403A91 ;printf
add esp, 8
xor eax, eax
retn
_main endp
例子:
源码:
int main()
{15+20;
int nVarOne = 0;
int nVarTwo = 0;
nVarOne = nVarOne+1;
nVarOne = 1+2;
nVarOne = nVarOne+nVarTwo;
printf("nVarOne = %d\r\n", nVarOne);
return 0;
}
Debug下:
mov [ebp+var_4], 0
mov [ebp+var_8], 0
mov eax, [ebp+var_4]
add eax, 1
mov [ebp+var_4], eax
mov [ebp+var_4], 3
mov ecx, [ebp+var_4]
add ecx, [ebp+var_8]
mov [ebp+var_4], ecx
mov edx, [ebp+var_4]
push edx
push offset Format ; "nVarOne = %d\r\n"
call _printf
mov [ebp+var_8], 0
mov eax, [ebp+var_4]
add eax, 1
mov [ebp+var_4], eax
mov [ebp+var_4], 3
mov ecx, [ebp+var_4]
add ecx, [ebp+var_8]
mov [ebp+var_4], ecx
mov edx, [ebp+var_4]
push edx
push offset Format ; "nVarOne = %d\r\n"
call _printf
Release下:
_main proc near
push 3push offset aNvaroneD ; "nVarOne = %d\r\n"
call sub_403A91 ;printf
add esp, 8
xor eax, eax
retn
_main endp
关于编译器的优化: 常量传播和常量折叠
常量传播: 编译器常常将编译期间可以计算出结果的变量转换成常量
常量折叠:对于常量表达式 编译器会在编译期间就计算出等式结果并予以替换