Title: Writing optimized code with Delphi
Question: A few technique for writing optimized code with Delphi
Answer:
IF Statements
-Comparisons with zero are generally translated to faster and more compact machine code than comparison with non-zero. Thus because "test" instruction (reg-reg, 2 bytes, 1 clock) is shorter than "cmp" instruction (reg-immed - 3 bytes, 1 clock). But if the value of variable to compare is not needed after the comparison, it is better to compare with (-1) than with 0. That is because compiler translates comparison with 0 to "test" instruction (2 bytes) and comparison with (-1) to "inc/dec" (1 byte)
var
sl: TStringList;
i: integer;
begin
sl := TStringList.Create;
try
sl.Add('1');
sl.Add('2');
sl.Add('3');
if sl.IndexOf('3') -1 then //Use ( -1) instead of (= 0) since value not needed any more
ShowMessage('test');
finally
sl.Destroy;
end;
end;
For loops
If finalValue changes in the loop
(for counter := initialValue to finalValue do statement)
Example:
The code bellow will cause "Index out of bounds exception".
var
sl: TStringList;
i: integer;
begin
sl := TStringList.Create;
try
sl.Add('1'); sl.Add('2'); sl.Add('3');
for i := 0 to Pred(sl.Count) do
if sl[i] = '2' then
sl.Delete(i);
finally
sl.Destroy;
end;
end;
Solution:
var
sl: TStringList;
i: integer;
begin
sl := TStringList.Create;
try
sl.Add('1'); sl.Add('2'); sl.Add('3');
for i := Pred(sl.Count) downto 0 do
if sl[i] = '2' then
sl.Delete(i);
finally
sl.Destroy;
end;
end;
Calculating loop exit condition
Delphi(5) compiler does not use Pentium loop instruction. It translates every loop exit condition to a zero check. In most cases that means duplicating the loop control variable (except when the source code does not use counter¡¯s real value any more (inside or after the loop)).
Depending on whether loop control variable value is used inside or after exiting the loop:
1.1. Not used - in this case loops control variable final values do not matter - D5 compiler will shift the loop control variable in a way that the loop exit condition would be "control variable = 0" (see example)
2.2. Used (and the loop control variables initial value final value)
3.a. If the control variable final value 1 the compiler will duplicate it (see example)
4.b. If the control variable final value = 1 no duplication code is generated (see example)
Therefore when possible preferably write downto loops with control variable final value = 1.
Note: in Delphi2 and 3 the loop control variable value was undefined after exiting the loop.