Avoiding implicit try finally section

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

This issue is no longer relevant with FPC > 1.9.5 from 2004-12-26

Note: On 2004-12-26 Peter Vreman fixed this in compiler. This means that starting from FPC 1.9.5 2004-12-26, this information is no longer relevant. With newer compiler timings of demo program on this page show no significant difference between Test_ResourceString and Test_ResourceString_Fast.

If you know of any other case where implicit try...finally section may be created and significantly affect speed of some code, please upddate this page. Otherwise, just ignore this issue if you're using FPC newer than 1.9.5 from 2004-12-26.

Sometimes it's important to know that compiler can wrap some code in implicit try ... finally section. 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

And below is a small demo program that

Time of Test_ResourceString:        107
Time of Test_ResourceString_Faster: 16
{$mode objfpc}

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

function Clock: Int64;
var Dummy: tms;
begin
 Clock := FpTimes(Dummy);
end;

resourcestring
  SResString = 'blah blah blah blah blah blah blah blah blah blah';

{ Note that Test_ResourceString and Test_ResourceString_Fast 
  do exactly the same thing. }

procedure Test_ResourceString(i: Integer);
begin
 if i = -1 then raise Exception.Create(SResString);
end;

procedure Test_ResourceString_Faster(i: Integer);

  procedure RaiseError;
  begin
   raise Exception.Create(SResString)
  end;

begin
 if i = -1 then RaiseError;
end;

{ Note that when I call Test_ResourceString and Test_ResourceString_Fast
  i is always >= 0 so Exception is never actually raised. }

const
  TestCount = 10000000;
var
  i: Integer;
  Start: Int64;
begin
 Start := Clock;
 for i := 0 to TestCount do Test_ResourceString(i);
 Writeln('Time of Test_ResourceString:        ', Clock - Start);
 
 Start := Clock;
 for i := 0 to TestCount do Test_ResourceString_Faster(i);
 Writeln('Time of Test_ResourceString_Faster: ', Clock - Start);
end.