让我们看一下代码优化前后的区别:
procedure test;
var
x,y,z: integer;
begin
x:= 1;
Inc(x);
y:= x;
z:= 0;
if (y = 1) then Inc(z);
end;
这是经过优化的汇编代码:
Project5.dpr.12: x:= 1
004085E8 B801000000 mov eax,$00000001
Project5.dpr.13: Inc(x)
004085ED 40 inc eax
Project5.dpr.18: if (y = 1) then Inc(z)
004085EE 48 dec eax //test to see if eax=1, triggers `jz` if true.
//Delphi put it in to facilitate the `if`, but
//is not smart enough to eliminate it :-)
Project5.dpr.19: end
004085EF C3 ret
以下是未经优化的代码:
Project5.dpr.11: begin //note that Delphi doesn't use registers, but the stack
//to keep variables.
004085E8 55 push ebp
004085E9 8BEC mov ebp,esp //init the stack frame.
004085EB 83C4F4 add esp,-$0c
Project5.dpr.12: x:= 1
004085EE C745FC01000000 mov [ebp-$04],$00000001
Project5.dpr.13: Inc(x)
004085F5 FF45FC inc dword ptr [ebp-$04]
Project5.dpr.14: y:= x
004085F8 8B45FC mov eax,[ebp-$04]
004085FB 8945F8 mov [ebp-$08],eax
Project5.dpr.17: z:= 0
004085FE 33C0 xor eax,eax
00408600 8945F4 mov [ebp-$0c],eax
Project5.dpr.18: if (y = 1) then Inc(z)
00408603 837DF801 cmp dword ptr [ebp-$08],$01
00408607 7503 jnz $0040860c
00408609 FF45F4 inc dword ptr [ebp-$0c]
Project5.dpr.19: end
0040860C 8BE5 mov esp,ebp //until the stack frame is dismantled.
0040860E 5D pop ebp
0040860F C3 ret
如果关闭优化,您的情况应该永远不会发生,但是...
您也可以在源代码中设置优化开/关:
{$Optimization on/off} or
{$O+/-}
如果这行代码在你的例程前面,它将覆盖全局设置。
http://docwiki.embarcadero.com/RADStudio/zh-cn/%E4%BC%98%E5%8C%96_(Delphi)