官术网_书友最值得收藏!

Optimization

The Optimization option controls code optimization. The possible values are On and Off. This setting can also be controlled with compiler directives {$OPTIMIZATION ON} and {$OPTIMIZATION OFF} or with equivalent {$O+} and {$O-}.

When optimization is enabled, the compiler optimizes generated code for speed. Optimizations are guaranteed not to change the behavior of the program. The only reason you may want to turn optimization off is to improve debugging. When optimization is turned on, debugging—especially stepping through the code and evaluating variables—may not be working correctly in all cases.

My approach is to turn optimization off during development, and on when building the release version.

The $O (or $OPTIMIZATION) directive can only turn optimization on or off for an entire method. You cannot turn optimization on or off for selected lines within a method.

To show the effect of different compiler options, I have written a CompilerOptions demo. When you click the Optimization button, the following code will be run twice—once with optimization turned on and once off.

The code initializes an array and then does some calculations on all of its elements. All of this is repeated 1,000 times because otherwise it is hard to measure differences. Modern CPUs are fast!

function NonOptimized: int64;
var
arr1: array [1..50000] of Integer;
i,j: Integer;
begin
for j := 1 to 1000 do
begin
for i := Low(arr1) to High(arr1) do
arr1[i] := i;
for i := Low(arr1) to High(arr1)-1 do
arr1[i] := arr1[i] + arr1[i+1];
end;
end;

The results will be different depending on the CPU speed and model, but on all computers the optimized version should be significantly faster. On my test machine, the optimized version runs approximately six times faster than the non-optimized! Here are the results:

Although you can turn compilation options on and off with compiler directives, Delphi provides no direct support for switching back to the previous state. You can, however, check whether a compilation option is currently turned on or off by using the {$IFOPT} compiler directive.

Then you can define or undefine some conditional compilation symbol that will tell you later what the original state of the compilation option was:

{$IFOPT O+}{$DEFINE OPTIMIZATION}{$ELSE}{$UNDEF OPTIMIZATION}{$ENDIF}
{$OPTIMIZATION ON}

When you want to restore the original state, use this conditional to turn the compilation option on or off:

{$IFDEF OPTIMIZATION}{$OPTIMIZATION ON}{$ELSE}{$OPTIMIZATION OFF}{$ENDIF}

This technique is used throughout the CompilerOptions demo with different compilation options.

主站蜘蛛池模板: 花莲县| 阳春市| 府谷县| 南昌县| 得荣县| 定日县| 绥江县| 威信县| 永康市| 保定市| 封开县| 普格县| 宜章县| 英山县| 铜鼓县| 罗山县| 青铜峡市| 元谋县| 禹州市| 和林格尔县| 平遥县| 金塔县| 乐安县| 乡城县| 应用必备| 大庆市| 临朐县| 长沙市| 五家渠市| 濉溪县| 上林县| 惠东县| 武鸣县| 沧州市| 赤峰市| 大同县| 垣曲县| 清徐县| 天镇县| 图木舒克市| 黔江区|