Sign in Join
Wiki copytemporary

Avoiding implicit try finally section: what changed

Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.

OldNewLine
11## Overview
22
33When optimizing code it helps to know that the [[Compiler|compiler]] will wrap certain code constructs in an implicit [[Try|try]] … [[Finally|finally]] statement. This is needed whenever you use [[Variable|variables]] such as [[Ansistring|AnsiString]], [[Variant]] or [[Dynamic array|dynamic arrays]] which require [[Initialization|initialization]] and [[Finalization|finalization]] (i.e. where the standard [[Procedure|procedures]] `initialize` and `finalize` are needed for correct allocation and release of acquired memory).
44
55For example, a procedure like
66
77``` pascal
88procedure doSomething;
99var
1010 msg: ansiString;
1111begin
1212 // do something with msg
1313end;
1414```
1515
1616is actually expanded by the compiler to look like this (difference highlighted):
1717
1818``` pascal
1919procedure doSomething;
2020var
2121 msg: ansiString;
2222begin
2323 initialize(msg);
2424 try
2525 // do something with msg
2626 finally
2727 finalize(msg);
2828 end;
2929end;
3030```
3131
3232The compiler thereby ensures that the reference count of `msg` will be properly decremented when `procedure doSomething` exits with [[Exceptions|exception]]. However, often this may have significant adverse effects on the generated code's speed.
3333
3434This is issue was a subject on the `fpc-devel` list in the [`TList` slowness classes](http://www.mail-archive.com/fpc-devel@lists.freepascal.org/msg01367.html) thread.
3535
3636Note, that temporary `ansiString` variables can be created *implicitly*. The only way to be completely certain about what actually is being done is to read the [[Assembler|assembler]] output.
3737
3838## Possible solutions
3939
4040- use [[$implicitExceptions|{$implicitexceptions off}]]: Ensure this applies to release versions only. Debugging can become cumbersome with that switch especially locating memory leaks and corruption.
4141- split off rarely used code that causes an implicit `try…finally` into separate procedures. (You can use nested procedures)
4242- use [[Const|const parameters]] rather than value parameters. This avoids the need to change `refcount` but temporary variables could still be an issue.
4343- use [[Global variables|global variables]]: You have to be careful with reentrancy issues here though and temporary variables could still be an issue.
4444- use non-reference-counted types like [[ShortString|shortstring]].
4545
4646## Risks and when to apply
4747
4848> **Warning:** These exception frames are generated for a reason. If you leave them out any exception in that code will leave a memory leak
4949
5050In 2007 [[sImplicitExceptions|{$implicitExceptions}]] was added to the [`strutils`](https://www.freepascal.org/docs-html/rtl/strutils/index.html) [[Unit|unit]]. For this, the following approach was followed:
5151
5252- A [[Routine|routine]] that calls a routine that [[Raise|raises]] exceptions is unsafe – e.g. [`strToInt`](https://www.freepascal.org/docs-html/rtl/sysutils/strtoint.html), but not [`strToIntDef`](https://www.freepascal.org/docs-html/rtl/sysutils/strtointdef.html).
5353- A routine that raises exceptions itself is unsafe.
5454- Very large routines are not worth the trouble, because of the risk and low gains – e.g. [date formatting](https://www.freepascal.org/docs-html/rtl/sysutils/datetimeroutines.html) routines.
5555- Floating point usage can raise exceptions that are converted into catchable exceptions by [[sysutils|sysUtils]]. I'm not sure if this really is sufficient reason, but I skipped floating point using routines initially for this reason.
5656
5757If you detect problems with these changes please contact Marco.
5858
5959## Demo program
6060
6161Below is a small demo [[Program|program]] that
6262
6363- When run, clearly shows that avoiding an implicit `try … finally`-block can make code a lot faster. When I run this program on my system, I get
6464
65-`time of fooNormal: 141`\
66-`time of fooFaster: 17`
65+```
66+time of fooNormal: 141
67+time of fooFaster: 17
68+```
6769
6870- Shows a trick how to avoid implicit `try … finally`-block (without changing the meaning or safety of the code) in some cases (when you don't need to actually use that [[Ansistring|AnsiString]]/[[Variant]]/[[Data type|something]] every time procedure is called but e.g. only if some parameter has some particular value).
6971
7072``` pascal
7173program implicitExceptionDemo;
7274
7375// for exceptions
7476{$mode objfpc}
7577// data type 'string' refers to 'ansistring'
7678{$longstrings on}
7779
7880uses
7981 {$IFDEF UNIX}
8082 BaseUnix, Unix, // needed only to implement clock()
8183 {$ENDIF}
8284 sysUtils;
8385
8486function clock(): int64;
8587{$IFDEF UNIX}
8688var
8789 dummy: tms;
8890begin
8991 clock := fpTimes(dummy);
9092end;
9193{$ELSE}
9294var
9395 TS: TTimeStamp;
9496begin
9597 TS := DateTimeToTimeStamp(Now);
9698 result := TS.Time;
9799end;
98100{$ENDIF}
99101
100102// When fooNormal() and fooFaster() are called
101103// i is always >= 0, so no exception is ever actually raised,
102104// and string constants are not really used.
103105
104106procedure fooNormal(i: integer);
105107var
106108 s: string;
107109begin
108110 if i = -1 then
109111 begin
110112 s := 'Some operation with AnsiString';
111113 raise Exception.Create(s);
112114 end;
113115end;
114116
115117procedure fooFaster(i: integer);
116118 //
117119 procedure RaiseError;
118120 var
119121 s: string;
120122 begin
121123 s := 'Some operation with AnsiString';
122124 raise Exception.Create(s);
123125 end;
124126 //
125127begin
126128 if i = -1 then
127129 begin
128130 RaiseError;
129131 end;
130132end;
131133
132134// M A I N =================================================
133135const
134136 testCount = 10000000;
135137var
136138 i: integer;
137139 start: int64;
138140begin
139141 // normal version
140142 start := clock();
141143 for i := 0 to testCount do
142144 begin
143145 fooNormal(i);
144146 end;
145147 writeLn('time of fooNormal: ', clock() - start);
146148
147149 // faster version
148150 start := clock();
149151 for i := 0 to testCount do
150152 begin
151153 fooFaster(i);
152154 end;
153155 writeLn('time of fooFaster: ', clock() - start);
154156end.
155157```
156158
157159By putting `raiseError` into a nested [[Scope|scope]] of `fooFaster`, exception handling does not become part of the main thread of execution.
158160
159161---
160162*From the Free Pascal wiki, page "Avoiding implicit try finally section", as it stood on 2024-01-22 after a change by N7800, out of the wiki's dump of 2024-05-26. Copyright stays with the author who wrote it, according to the old wiki's [[Licensing]] page. If you have concerns about this material, [message the admin](/wiki-contact).*
161163Category: Software security

Back to history