Avoiding implicit try finally section

This is an old revision of Avoiding implicit try finally section, edited by Chronos at . The current revision is 30014.

code highlight and category

Sometimes it's useful to know that compiler can wrap some code in implicit try ... finally block. Essentialy this is needed when you use variable of any type that must be initialized / finalized (i.e. standard procedures Initialize() and Finalize() do something meaningful with it), like AnsiStrings or Variants or dynamic arrays. Or (only in FPC earlier than 2004-12-26) resource strings.

E.g. procedure like <delphi>procedure P; var

 S: AnsiString;

begin

 ... do something with S ...

end;</delphi>

is actually compiled like

<delphi>procedure P; var

 S: AnsiString;

begin

Initialize(S);
try
 ... do something with S ...
finally Finalize(S) end;

end;</delphi>

This is needed, to be sure that reference-count of S will be properly decremented when procedure P will exit with exception. But in some cases this can significantly affect the speed of given code.

Here's a link to archived discussion on fpc-devel list regarding this issue, with subject "TList slowness in classes" : http://www.mail-archive.com/fpc-devel@lists.freepascal.org/msg01367.html

Note that ansistring temp vars can be created implicitly. The only real way to be sure what's going on is to read the asm output.

Possible solutions

RISKS and when to apply

These exception frames are generated for a reason. If you leave them out any exception in that code will leave a memory leak

Recently (2007-10-14 in 2.3.x branch) I added $implicitexceptions to the strutils unit, sysutils will follow if this doesn't raise serious problems. For this, the following approach was followed:

If you detect problems with these changes please contact Marco.

Demo program

And below is a small demo program that

Time of Foo_Normal: 141
Time of Foo_Faster: 17

<delphi>{$mode objfpc}{$H+}

uses

 {BaseUnix, Unix needed only to implement Clock} BaseUnix, Unix,
 SysUtils;

function Clock: Int64; var Dummy: tms; begin

Clock := FpTimes(Dummy);

end;

procedure Foo_Normal(i: Integer); var S: string; begin

if i = -1 then
begin
 S := 'Some operation with AnsiString';
 raise Exception.Create(S);
end;

end;

procedure Foo_Faster(i: Integer);

 procedure RaiseError;
 var S: string;
 begin
  S := 'Some operation with AnsiString';
  raise Exception.Create(S);
 end;

begin

if i = -1 then RaiseError;

end;

{ Note that when I call Foo_Normal and Foo_ResourceString

 i is always >= 0 so Exception is never actually raised.
 So string constants SNormal and SResString are not really used. }

const

 TestCount = 10000000;

var

 i: Integer;
 Start: Int64;

begin

Start := Clock;
for i := 0 to TestCount do Foo_Normal(i);
Writeln('Time of Foo_Normal: ', Clock - Start);
Start := Clock;
for i := 0 to TestCount do Foo_Faster(i);
Writeln('Time of Foo_Faster: ', Clock - Start);

end.</delphi>