Sign in Join
Wiki copytemporary

Avoiding implicit try finally section: what changed

Revision 2 to 3. 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-```
65+```text
6666time of fooNormal: 141
6767time of fooFaster: 17
6868```
6969
7070- 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).
7171
7272``` pascal
7373program implicitExceptionDemo;
7474
7575// for exceptions
7676{$mode objfpc}
7777// data type 'string' refers to 'ansistring'
7878{$longstrings on}
7979
8080uses
8181 {$IFDEF UNIX}
8282 BaseUnix, Unix, // needed only to implement clock()
8383 {$ENDIF}
8484 sysUtils;
8585
8686function clock(): int64;
8787{$IFDEF UNIX}
8888var
8989 dummy: tms;
9090begin
9191 clock := fpTimes(dummy);
9292end;
9393{$ELSE}
9494var
9595 TS: TTimeStamp;
9696begin
9797 TS := DateTimeToTimeStamp(Now);
9898 result := TS.Time;
9999end;
100100{$ENDIF}
101101
102102// When fooNormal() and fooFaster() are called
103103// i is always >= 0, so no exception is ever actually raised,
104104// and string constants are not really used.
105105
106106procedure fooNormal(i: integer);
107107var
108108 s: string;
109109begin
110110 if i = -1 then
111111 begin
112112 s := 'Some operation with AnsiString';
113113 raise Exception.Create(s);
114114 end;
115115end;
116116
117117procedure fooFaster(i: integer);
118118 //
119119 procedure RaiseError;
120120 var
121121 s: string;
122122 begin
123123 s := 'Some operation with AnsiString';
124124 raise Exception.Create(s);
125125 end;
126126 //
127127begin
128128 if i = -1 then
129129 begin
130130 RaiseError;
131131 end;
132132end;
133133
134134// M A I N =================================================
135135const
136136 testCount = 10000000;
137137var
138138 i: integer;
139139 start: int64;
140140begin
141141 // normal version
142142 start := clock();
143143 for i := 0 to testCount do
144144 begin
145145 fooNormal(i);
146146 end;
147147 writeLn('time of fooNormal: ', clock() - start);
148148
149149 // faster version
150150 start := clock();
151151 for i := 0 to testCount do
152152 begin
153153 fooFaster(i);
154154 end;
155155 writeLn('time of fooFaster: ', clock() - start);
156156end.
157157```
158158
159159By putting `raiseError` into a nested [[Scope|scope]] of `fooFaster`, exception handling does not become part of the main thread of execution.
160160
161161---
162162*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).*
163163Category: Software security

Back to history