Difference between revisions of "Avoiding implicit try finally section"
(review) |
m (syntax highlighting with other colors) |
||
Line 1: | Line 1: | ||
{{Avoiding implicit try finally section}} | {{Avoiding implicit try finally section}} | ||
− | == | + | == overview == |
− | When optimizing code it helps to know that the compiler will wrap certain code constructs in an implicit < | + | When optimizing code it helps to know that the compiler will wrap certain code constructs in an implicit <syntaxhighlight lang="pascal" enclose="none">try … finally</syntaxhighlight>-block. |
− | This is needed whenever you use variables such as [[Ansistring|< | + | This is needed whenever you use variables such as [[Ansistring|<syntaxhighlight lang="pascal" enclose="none">ansiString</syntaxhighlight>s]], [[Variant|<syntaxhighlight lang="pascal" enclose="none">variant</syntaxhighlight>s]] or [[Dynamic array|dynamic arrays]] which require [[Initialization|initialization]] and [[Finalization|finalization]] (i.e. where the standard procedures <syntaxhighlight lang="pascal" enclose="none">initialize</syntaxhighlight> and <syntaxhighlight lang="pascal" enclose="none">finalize</syntaxhighlight> are needed for correct allocation and release of acquired memory). |
For example, a procedure like | For example, a procedure like | ||
− | <syntaxhighlight> | + | <syntaxhighlight lang="pascal"> |
procedure doSomething; | procedure doSomething; | ||
var | var | ||
Line 14: | Line 14: | ||
end; | end; | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | is actually expanded by the compiler to look like this: | + | is actually expanded by the compiler to look like this (difference highlighted): |
− | <syntaxhighlight> | + | <syntaxhighlight lang="pascal" highlight="5-6,8-10"> |
procedure doSomething; | procedure doSomething; | ||
var | var | ||
Line 29: | Line 29: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | The compiler thereby ensures that the reference count of < | + | The compiler thereby ensures that the reference count of <syntaxhighlight lang="pascal" enclose="none">msg</syntaxhighlight> will be properly decremented when <syntaxhighlight lang="pascal" enclose="none">procedure doSomething</syntaxhighlight> exits with exception[s]?. |
However, often this may have significant adverse effects on the generated code's speed. | However, often this may have significant adverse effects on the generated code's speed. | ||
− | This is issue was a subject on the < | + | This is issue was a subject on the <tt>fpc-devel</tt> list in the [http://www.mail-archive.com/fpc-devel@lists.freepascal.org/msg01367.html <syntaxhighlight lang="pascal" enclose="none">TList</syntaxhighlight> slowness classes] thread. |
− | Note, that temporary < | + | Note, that temporary <syntaxhighlight lang="pascal" enclose="none">ansiString</syntaxhighlight> variables can be created ''implicitly''. |
The only way to be completely certain about what actually is being done is to read the assembler output. | The only way to be completely certain about what actually is being done is to read the assembler output. | ||
== possible solutions == | == possible solutions == | ||
− | * use [[sImplicitExeptions|< | + | * use [[sImplicitExeptions|<syntaxhighlight lang="pascal" enclose="none">{$implicitexceptions off}</syntaxhighlight>]]: Ensure this applies to release versions only. Debugging can become cumbersome with that switch especially locating memory leaks and corruption. |
− | * split off rarely used code that causes an implicit < | + | * split off rarely used code that causes an implicit <syntaxhighlight lang="pascal" enclose="none">try…finally</syntaxhighlight> into separate procedures. (You can use procedures in procedures) |
− | * use [[Const#const parameter|const parameters]] rather than value parameters. This avoids the need to change < | + | * use [[Const#const parameter|<syntaxhighlight lang="pascal" enclose="none">const</syntaxhighlight> parameters]] rather than value parameters. This avoids the need to change <syntaxhighlight lang="pascal" enclose="none">refcount</syntaxhighlight> but temporary variables could still be an issue. |
* use [[Global variables|global variables]]: You have to be careful with reentrancy issues here though and temporary variables could still be an issue. | * use [[Global variables|global variables]]: You have to be careful with reentrancy issues here though and temporary variables could still be an issue. | ||
− | * use non-reference-counted types like [[Shortstring|< | + | * use non-reference-counted types like [[Shortstring|<syntaxhighlight lang="pascal" enclose="none">shortstring</syntaxhighlight>s]]. |
== risks and when to apply == | == risks and when to apply == | ||
Line 48: | Line 48: | ||
{{Warning|These exception frames are generated for a reason. If you leave them out any exception in that code will leave a memory leak}} | {{Warning|These exception frames are generated for a reason. If you leave them out any exception in that code will leave a memory leak}} | ||
− | In 2007 [[sImplicitExceptions|< | + | In 2007 [[sImplicitExceptions|<syntaxhighlight lang="pascal" enclose="none">{$implicitExceptions}</syntaxhighlight>]] was added to the {{Doc|package=RTL|unit=strutils|text=<syntaxhighlight lang="pascal" enclose="none">strutils</syntaxhighlight> unit}}. |
− | Meanwhile, {{Doc|package=RTL|unit=sysutils|tetx=< | + | Meanwhile, {{Doc|package=RTL|unit=sysutils|tetx=<syntaxhighlight lang="pascal" enclose="none">sysUtils</syntaxhighlight>}} has probably followed. |
For this, the following approach was followed: | For this, the following approach was followed: | ||
− | * A routine that calls a routine that raises exceptions is unsafe – e.g. {{Doc|package=RTL|unit=sysutils|identifier=strtoint|text=< | + | * A routine that calls a routine that raises exceptions is unsafe – e.g. {{Doc|package=RTL|unit=sysutils|identifier=strtoint|text=<syntaxhighlight lang="pascal" enclose="none">strToInt</syntaxhighlight>}}, but not {{Doc|package=RTL|unit=sysutils|identifier=strtointdef|text=<syntaxhighlight lang="pascal" enclose="none">strToIntDef</syntaxhighlight>}}. |
* A routine that raises exceptions itself is unsafe. | * A routine that raises exceptions itself is unsafe. | ||
* Very large routines are not worth the trouble, because of the risk and low gains – e.g. {{Doc|package=RTL|unit=sysutils|identifier=datetimeroutines|text=date formatting}} routines. | * Very large routines are not worth the trouble, because of the risk and low gains – e.g. {{Doc|package=RTL|unit=sysutils|identifier=datetimeroutines|text=date formatting}} routines. | ||
− | * Floating point usage can raise exceptions that are converted into catchable exceptions by [[sysutils|< | + | * Floating point usage can raise exceptions that are converted into catchable exceptions by [[sysutils|<syntaxhighlight lang="pascal" enclose="none">sysUtils</syntaxhighlight>]]. I'm not sure if this really is sufficient reason, but I skipped floating point using routines initially for this reason. |
If you detect problems with these changes please contact [[User:Marcov|Marco]]. | If you detect problems with these changes please contact [[User:Marcov|Marco]]. | ||
Line 65: | Line 65: | ||
time of fooNormal: 141 | time of fooNormal: 141 | ||
time of fooFaster: 17 | time of fooFaster: 17 | ||
− | * Shows a trick how to avoid implicit < | + | * Shows a trick how to avoid implicit <syntaxhighlight lang="pascal" enclose="none">try … finally</syntaxhighlight>-block (without changing the meaning or safety of the code) in some cases (when you don't need to actually use that [[Ansistring|<syntaxhighlight lang="pascal" enclose="none">AnsiString</syntaxhighlight>]]/[[Variant|<syntaxhighlight lang="pascal" enclose="none">Variant</syntaxhighlight>]]/[[Data type|something]] every time procedure is called but e.g. only if some parameter has some particular value). |
− | <syntaxhighlight> | + | <syntaxhighlight lang="pascal" line start="0"> |
program implicitExceptionDemo(input, output, stderr); | program implicitExceptionDemo(input, output, stderr); | ||
Line 141: | Line 141: | ||
</syntaxhighlight> | </syntaxhighlight> | ||
− | By putting < | + | By putting <syntaxhighlight lang="pascal" enclose="none">raiseError</syntaxhighlight> into a nested [[Scope|scope]] of <syntaxhighlight lang="pascal" enclose="none">fooFaster</syntaxhighlight>, exception handling does not become part of the main thread of execution. |
[[Category:Tutorials]] | [[Category:Tutorials]] | ||
[[Category:FPC]] | [[Category:FPC]] |
Revision as of 00:21, 12 February 2018
│
English (en) │
suomi (fi) │
Bahasa Indonesia (id) │
русский (ru) │
overview
When optimizing code it helps to know that the compiler will wrap certain code constructs in an implicit try … finally
-block.
This is needed whenever you use variables such as ansiString
s, variant
s or dynamic arrays which require initialization and finalization (i.e. where the standard procedures initialize
and finalize
are needed for correct allocation and release of acquired memory).
For example, a procedure like
procedure doSomething;
var
msg: ansiString;
begin
// do something with msg
end;
is actually expanded by the compiler to look like this (difference highlighted):
procedure doSomething;
var
msg: ansiString;
begin
initialize(msg);
try
// do something with msg
finally
finalize(msg);
end;
end;
The compiler thereby ensures that the reference count of msg
will be properly decremented when procedure doSomething
exits with exception[s]?.
However, often this may have significant adverse effects on the generated code's speed.
This is issue was a subject on the fpc-devel list in the TList
slowness classes thread.
Note, 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 output.
possible solutions
- use
{$implicitexceptions off}
: Ensure this applies to release versions only. Debugging can become cumbersome with that switch especially locating memory leaks and corruption. - split off rarely used code that causes an implicit
try…finally
into separate procedures. (You can use procedures in procedures) - use
const
parameters rather than value parameters. This avoids the need to changerefcount
but temporary variables could still be an issue. - use global variables: You have to be careful with reentrancy issues here though and temporary variables could still be an issue.
- use non-reference-counted types like
shortstring
s.
risks and when to apply
Warning: These exception frames are generated for a reason. If you leave them out any exception in that code will leave a memory leak
In 2007 {$implicitExceptions}
was added to the strutils
unit.
Meanwhile, sysutils has probably followed.
For this, the following approach was followed:
- A routine that calls a routine that raises exceptions is unsafe – e.g.
strToInt
, but notstrToIntDef
. - A routine that raises exceptions itself is unsafe.
- Very large routines are not worth the trouble, because of the risk and low gains – e.g. date formatting routines.
- Floating point usage can raise exceptions that are converted into catchable exceptions by
sysUtils
. I'm not sure if this really is sufficient reason, but I skipped floating point using routines initially for this reason.
If you detect problems with these changes please contact Marco.
demo program
Below is a small demo program that
- 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
time of fooNormal: 141 time of fooFaster: 17
- 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 thatAnsiString
/Variant
/something every time procedure is called but e.g. only if some parameter has some particular value).
0program implicitExceptionDemo(input, output, stderr);
1
2// for exceptions
3{$mode objfpc}
4// data type 'string' refers to 'ansistring'
5{$longstrings on}
6
7uses
8 // baseUnix, unix needed only to implement clock
9 BaseUnix, Unix,
10 sysUtils;
11
12function clock(): int64;
13var
14 dummy: tms;
15begin
16 clock := fpTimes(dummy);
17end;
18
19// Note: when fooNormal and fooFaster are called
20// i is always >= 0, so no exception is ever actually raised.
21// So string constants SNormal and SResString are not really used.
22
23procedure fooNormal(i: integer);
24var
25 s: string;
26begin
27 if i = -1 then
28 begin
29 s := 'Some operation with AnsiString';
30 raise exception.create(s);
31 end;
32end;
33
34procedure fooFaster(i: integer);
35 procedure raiseError;
36 var
37 s: string;
38 begin
39 s := 'Some operation with AnsiString';
40 raise exception.create(s);
41 end;
42begin
43 if i = -1 then
44 begin
45 raiseError;
46 end;
47end;
48
49
50// M A I N =================================================
51const
52 testCount = 10000000;
53var
54 i: integer;
55 start: int64;
56begin
57 start := clock();
58 for i := 0 to testCount do
59 begin
60 fooNormal(i);
61 end;
62 writeLn('time of fooNormal: ', clock() - start);
63
64 start := clock();
65 for i := 0 to testCount do
66 begin
67 fooFaster(i);
68 end;
69 writeLn('time of fooFaster: ', clock() - start);
70end.
By putting raiseError
into a nested scope of fooFaster
, exception handling does not become part of the main thread of execution.