Avoiding implicit try finally section: what changed
Revision 1 to 2. Removed lines have a minus sign; added lines have a plus sign.
| Old | New | Line | |
|---|---|---|---|
| 1 | 1 | ## Overview | |
| 2 | 2 | ||
| 3 | 3 | When 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). | |
| 4 | 4 | ||
| 5 | 5 | For example, a procedure like | |
| 6 | 6 | ||
| 7 | 7 | ``` pascal | |
| 8 | 8 | procedure doSomething; | |
| 9 | 9 | var | |
| 10 | 10 | msg: ansiString; | |
| 11 | 11 | begin | |
| 12 | 12 | // do something with msg | |
| 13 | 13 | end; | |
| 14 | 14 | ``` | |
| 15 | 15 | ||
| 16 | 16 | is actually expanded by the compiler to look like this (difference highlighted): | |
| 17 | 17 | ||
| 18 | 18 | ``` pascal | |
| 19 | 19 | procedure doSomething; | |
| 20 | 20 | var | |
| 21 | 21 | msg: ansiString; | |
| 22 | 22 | begin | |
| 23 | 23 | initialize(msg); | |
| 24 | 24 | try | |
| 25 | 25 | // do something with msg | |
| 26 | 26 | finally | |
| 27 | 27 | finalize(msg); | |
| 28 | 28 | end; | |
| 29 | 29 | end; | |
| 30 | 30 | ``` | |
| 31 | 31 | ||
| 32 | 32 | The 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. | |
| 33 | 33 | ||
| 34 | 34 | This 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. | |
| 35 | 35 | ||
| 36 | 36 | 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|assembler]] output. | |
| 37 | 37 | ||
| 38 | 38 | ## Possible solutions | |
| 39 | 39 | ||
| 40 | 40 | - use [[$implicitExceptions|{$implicitexceptions off}]]: Ensure this applies to release versions only. Debugging can become cumbersome with that switch especially locating memory leaks and corruption. | |
| 41 | 41 | - split off rarely used code that causes an implicit `try…finally` into separate procedures. (You can use nested procedures) | |
| 42 | 42 | - use [[Const|const parameters]] rather than value parameters. This avoids the need to change `refcount` but temporary variables could still be an issue. | |
| 43 | 43 | - use [[Global variables|global variables]]: You have to be careful with reentrancy issues here though and temporary variables could still be an issue. | |
| 44 | 44 | - use non-reference-counted types like [[ShortString|shortstring]]. | |
| 45 | 45 | ||
| 46 | 46 | ## Risks and when to apply | |
| 47 | 47 | ||
| 48 | 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 | |
| 49 | 49 | ||
| 50 | 50 | In 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: | |
| 51 | 51 | ||
| 52 | 52 | - 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). | |
| 53 | 53 | - A routine that raises exceptions itself is unsafe. | |
| 54 | 54 | - 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. | |
| 55 | 55 | - 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. | |
| 56 | 56 | ||
| 57 | 57 | If you detect problems with these changes please contact Marco. | |
| 58 | 58 | ||
| 59 | 59 | ## Demo program | |
| 60 | 60 | ||
| 61 | 61 | Below is a small demo [[Program|program]] that | |
| 62 | 62 | ||
| 63 | 63 | - 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 | |
| 64 | 64 | ||
| 65 | - | ||
| 66 | - | ||
| 65 | + | ``` | |
| 66 | + | time of fooNormal: 141 | |
| 67 | + | time of fooFaster: 17 | |
| 68 | + | ``` | |
| 67 | 69 | ||
| 68 | 70 | - 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). | |
| 69 | 71 | ||
| 70 | 72 | ``` pascal | |
| 71 | 73 | program implicitExceptionDemo; | |
| 72 | 74 | ||
| 73 | 75 | // for exceptions | |
| 74 | 76 | {$mode objfpc} | |
| 75 | 77 | // data type 'string' refers to 'ansistring' | |
| 76 | 78 | {$longstrings on} | |
| 77 | 79 | ||
| 78 | 80 | uses | |
| 79 | 81 | {$IFDEF UNIX} | |
| 80 | 82 | BaseUnix, Unix, // needed only to implement clock() | |
| 81 | 83 | {$ENDIF} | |
| 82 | 84 | sysUtils; | |
| 83 | 85 | ||
| 84 | 86 | function clock(): int64; | |
| 85 | 87 | {$IFDEF UNIX} | |
| 86 | 88 | var | |
| 87 | 89 | dummy: tms; | |
| 88 | 90 | begin | |
| 89 | 91 | clock := fpTimes(dummy); | |
| 90 | 92 | end; | |
| 91 | 93 | {$ELSE} | |
| 92 | 94 | var | |
| 93 | 95 | TS: TTimeStamp; | |
| 94 | 96 | begin | |
| 95 | 97 | TS := DateTimeToTimeStamp(Now); | |
| 96 | 98 | result := TS.Time; | |
| 97 | 99 | end; | |
| 98 | 100 | {$ENDIF} | |
| 99 | 101 | ||
| 100 | 102 | // When fooNormal() and fooFaster() are called | |
| 101 | 103 | // i is always >= 0, so no exception is ever actually raised, | |
| 102 | 104 | // and string constants are not really used. | |
| 103 | 105 | ||
| 104 | 106 | procedure fooNormal(i: integer); | |
| 105 | 107 | var | |
| 106 | 108 | s: string; | |
| 107 | 109 | begin | |
| 108 | 110 | if i = -1 then | |
| 109 | 111 | begin | |
| 110 | 112 | s := 'Some operation with AnsiString'; | |
| 111 | 113 | raise Exception.Create(s); | |
| 112 | 114 | end; | |
| 113 | 115 | end; | |
| 114 | 116 | ||
| 115 | 117 | procedure fooFaster(i: integer); | |
| 116 | 118 | // | |
| 117 | 119 | procedure RaiseError; | |
| 118 | 120 | var | |
| 119 | 121 | s: string; | |
| 120 | 122 | begin | |
| 121 | 123 | s := 'Some operation with AnsiString'; | |
| 122 | 124 | raise Exception.Create(s); | |
| 123 | 125 | end; | |
| 124 | 126 | // | |
| 125 | 127 | begin | |
| 126 | 128 | if i = -1 then | |
| 127 | 129 | begin | |
| 128 | 130 | RaiseError; | |
| 129 | 131 | end; | |
| 130 | 132 | end; | |
| 131 | 133 | ||
| 132 | 134 | // M A I N ================================================= | |
| 133 | 135 | const | |
| 134 | 136 | testCount = 10000000; | |
| 135 | 137 | var | |
| 136 | 138 | i: integer; | |
| 137 | 139 | start: int64; | |
| 138 | 140 | begin | |
| 139 | 141 | // normal version | |
| 140 | 142 | start := clock(); | |
| 141 | 143 | for i := 0 to testCount do | |
| 142 | 144 | begin | |
| 143 | 145 | fooNormal(i); | |
| 144 | 146 | end; | |
| 145 | 147 | writeLn('time of fooNormal: ', clock() - start); | |
| 146 | 148 | ||
| 147 | 149 | // faster version | |
| 148 | 150 | start := clock(); | |
| 149 | 151 | for i := 0 to testCount do | |
| 150 | 152 | begin | |
| 151 | 153 | fooFaster(i); | |
| 152 | 154 | end; | |
| 153 | 155 | writeLn('time of fooFaster: ', clock() - start); | |
| 154 | 156 | end. | |
| 155 | 157 | ``` | |
| 156 | 158 | ||
| 157 | 159 | By putting `raiseError` into a nested [[Scope|scope]] of `fooFaster`, exception handling does not become part of the main thread of execution. | |
| 158 | 160 | ||
| 159 | 161 | --- | |
| 160 | 162 | *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).* | |
| 161 | 163 | Category: Software security |
