<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>DelphiTools.info &#187; Debug</title>
	<atom:link href="http://delphitools.info/tag/debug/feed/" rel="self" type="application/rss+xml" />
	<link>http://delphitools.info</link>
	<description>SamplingProfiler and other Delphi tools</description>
	<lastBuildDate>Sat, 04 Sep 2010 07:00:59 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.0.1</generator>
		<item>
		<title>All hail the &#8220;const&#8221; parameters!</title>
		<link>http://delphitools.info/2010/07/28/all-hail-the-const-parameters/</link>
		<comments>http://delphitools.info/2010/07/28/all-hail-the-const-parameters/#comments</comments>
		<pubDate>Wed, 28 Jul 2010 06:16:44 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[Compiler]]></category>
		<category><![CDATA[const]]></category>
		<category><![CDATA[CPU]]></category>
		<category><![CDATA[Debug]]></category>
		<category><![CDATA[Delphi Optimization]]></category>
		<category><![CDATA[Profiler]]></category>

		<guid isPermaLink="false">http://delphitools.info/?p=483</guid>
		<description><![CDATA[Passing parameters as &#8220;const&#8221; is a classic Delphi optimization trick, but the mechanisms behind that &#8220;trick&#8221; go beyond cargo-cult recipes, and may actually stumble into the &#8220;good practice&#8221; territory. Why does it work? The most well known case is &#8220;const String&#8220;, for which the compiler than takes advantage of the &#8220;const&#8221; to pass the String [...]]]></description>
			<content:encoded><![CDATA[<p>Passing parameters as &#8220;<em>const</em>&#8221; is a classic Delphi optimization trick, but the mechanisms behind that &#8220;trick&#8221; go beyond <a href="http://en.wikipedia.org/wiki/Cargo_cult_programming">cargo-cult</a> recipes, and may actually stumble into the &#8220;good practice&#8221; territory.</p>
<p><strong>Why does it work?</strong></p>
<p>The most well known case is &#8220;<em>const String</em>&#8220;, for which the compiler than takes advantage of the &#8220;<em>const</em>&#8221; to pass the <em>String</em> reference directly (as a pointer)&#8230; and without increasing the reference counter.</p>
<p>To illustrate what the reference counting implies, here are two screen-shots from the CPU disassembly view, taken in Delphi 6, but the recent compilers up to Delphi 2010 at least behave in a similar fashion (just with the Unicode version of the functions).<br />
I&#8217;ve made a pseudo-function, with only one <em>String </em>parameter that calls a single function (here <em>Length()</em>, which isn&#8217;t inlined in Delphi 6, and corresponds to <em>LStrLen</em>), guess which CPU disassembly corresponds to &#8220;<em>Test(const a : String)</em>&#8221; and which to &#8220;<em>Test(a : String)</em>&#8221;</p>
<table style="width: 100%;">
<tbody>
<tr>
<td width="50%" align="center"><a href="http://delphitools.info/wp-content/uploads/2010/07/refcount1.png"><a href="http://delphitools.info/wp-content/uploads/2010/07/refcount1.png"><img class="alignnone size-medium wp-image-484" title="refcount1" src="http://delphitools.info/wp-content/uploads/2010/07/refcount1-247x300.png" alt="" width="247" height="300" /></a></a></td>
<td width="50%" align="center" valign="top"><a href="http://delphitools.info/wp-content/uploads/2010/07/refcount2.png"><img class="alignnone size-full wp-image-485" title="refcount2" src="http://delphitools.info/wp-content/uploads/2010/07/refcount2.png" alt="" width="323" height="45" /></a></td>
</tr>
</tbody>
</table>
<p>What you&#8217;re seeing on the left is an implicit <em>try&#8230;finally</em> construct which is used to protect the reference counting (<em>LStrAddRef/LStrClr</em>) on the implicit local variable used to store the <em>String </em>parameter. If you have such calls nested a few levels deep (not uncommon in object-oriented code), you could accumulate quite some overhead.<br />
Also not see here but hidden within the <em>AddRef </em>and <em>Clr </em>calls are bus locks, which may hit you disproportionately in multi-threading scenarios.</p>
<p>And what if you&#8217;re modifying the passed <em>String</em>? Can you forego the &#8220;<em>const</em>&#8220;? Well no, the extra overhead is still there, and using a &#8220;<em>const</em>&#8221; still beneficial.</p>
<p><em>String </em>isn&#8217;t the only type affected, there are similar gains for all reference counted types (interfaces, dynamic arrays, records holding reference-counted types). And when passing a record as &#8220;<em>const</em>&#8220;, there is an additional gain in the lack of defensive copying of the record (the larger the record, the greater the gain).</p>
<p>For ordinal and numeric types, there is no compiler optimization (yet), but it can be good practice to mark them as &#8220;<em>const</em>&#8220;, not in the optimistic hope that someday the compiler will optimize it, but to ease up debugging and code writing. Copies of those parameters (when you want to modify them in the function body) are typically handled adequately by the compiler (and often enough comes for free), so don&#8217;t let performance considerations hold you.</p>
<p>There is one case in which using &#8220;<em>const</em>&#8221; could have adverse effects, but it involves global variables which you would modify or release during the call&#8230; so you don&#8217;t really need to know more about it, do you? <img src='http://delphitools.info/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> </p>
<p><strong>How does it manifests itself in Profiling?</strong></p>
<p>A missing &#8220;<em>const</em>&#8221; can manifests itself in different ways during profiling, for <em>String</em>, <em>Interface </em>and dynamic array types, you&#8217;ll usually see it via the relevant <em>xxxAddRef </em>or <em>xxxClr </em>functions (the obvious case) and via time spent in <em>begin/end</em> (the less obvious case). Depending on how many functions calls with the reference counting are involved in your inner loop, none of the above may come ahead, even if calls and reference counting are an issue: the time spent will be spread over the above functions and your various <em>begin/end</em> sections.<br />
For record parameters, the lack of &#8220;<em>const</em>&#8221; could materialize itself in &#8220;<em>Move</em>&#8220;, or other data copying costs (large records will be moved, smaller ones can be copied via ad-hoc in-place code by the compiler).</p>
<p>In multi-threading, things can be a little less obvious, as rather than the reference counting and exception frame, it could be the bus locks hitting you, or sometimes worse, inter-CPU traffic to pass around the values of the reference counter.</p>
<p>Multi-threading&#8217;s worst case would be referring to the same string field from multiple threads, and passing that string around in functions without &#8220;<em>const</em>&#8221; parameters, thus repeatedly hitting the reference counter of that string from multiple threads at the same time, resulting in extra inter-CPUs traffic to share the value of that reference counter.</p>
<p>In such cases, &#8220;<em>const</em>&#8221; can help, but it will often not be enough, you&#8217;ll also have to look for functions/methods that return strings with an unnecessary reference counting, like when getting your strings from a <em>TStringList</em>.</p>
<p><strong>Good Practice</strong><br class="spacer_" /></p>
<p>Usually I tend to &#8220;<em>const</em>&#8221; just about every parameter that isn&#8217;t &#8220;<em>var</em>&#8221; or an object, this isn&#8217;t just  to pre-emptively alleviate possible performance issues, but also to gain something valuable when debugging and writing a function&#8217;s body: untouched input parameters, wherever you are in the function&#8217;s body. This means not just in the function&#8217;s body, but also when in the functions called by the function.</p>
<p>And that&#8217;s the key point to remember about &#8220;<em>const</em>&#8221; parameter: it&#8217;s here to state that a parameter will be left unchanged inside the body, something which allows the compiler to optimize it&#8217;s output, and the developer to optimize his thought process too. Qualifying all your parameters as either &#8220;<em>const</em>&#8221; or &#8220;<em>var</em>&#8221; makes your intentions obvious.</p>
<p>So IME, it&#8217;s not worth it to hoard your keystrokes, best spend them on &#8220;<em>const</em>&#8221; and explicit local variables when you really need to alter those input parameters.<br />
Whoever has to maintain your code will be thankful.</p>
<p><strong>Object parameters</strong></p>
<p>There is one case I&#8217;ve not mentioned in all the above, the case of object parameters (and class references). It&#8217;s a special case because when you pass an object as &#8220;<em>const</em>&#8220;, you&#8217;re not making any promises of not keeping the object constant, but just keeping the underlying variable (pointer) constant. This is unlike other languages. There is also a risk of confusion when your code will be read by developers not really familiar with the underlying pointer-based mechanics of objects (and they are more common than you may think, even, and maybe more so in highly OO languages).</p>
<p>So for objects, unless you want to spend a lot of time educating, my rule of thumb is to avoid &#8220;<em>const</em>&#8221; or &#8220;<em>var</em>&#8221; for object parameters.</p>
<p><strong>Beyond &#8220;const&#8221; parameters</strong></p>
<p>Const&#8217;ing your parameters will eliminate some defensive copying, implicit <em>try&#8230;finally</em>, and reference counting overhead, but it leaves open another field of similar inefficiencies: that of return values.</p>
<p>Alas there is no &#8220;<em>const Result</em>&#8221; syntax, which would allow to state that your result can&#8217;t be altered in any way (a sort of strict immutability if you will). Thus whenever you have a function returning a <em>String </em>f.i., you&#8217;ll end up triggering the implicit reference counting and exception machinery if you&#8217;re not careful (like in <a href="http://delphitools.info/2009/05/06/code-optimization-go-for-the-jugular/">this case</a>)&#8230;</p>
<p>There are strategies to tackle this issue, but none of them are as simple as adding a &#8220;<em>const</em>&#8220;, and most of them come with sacrifices&#8230; so, let them be food for other articles.</p>
]]></content:encoded>
			<wfw:commentRss>http://delphitools.info/2010/07/28/all-hail-the-const-parameters/feed/</wfw:commentRss>
		<slash:comments>15</slash:comments>
		</item>
		<item>
		<title>Don&#8217;t abuse FreeAndNil anymore</title>
		<link>http://delphitools.info/2010/02/06/dont-abuse-freeandnil-anymore/</link>
		<comments>http://delphitools.info/2010/02/06/dont-abuse-freeandnil-anymore/#comments</comments>
		<pubDate>Sat, 06 Feb 2010 15:41:21 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[Tips]]></category>
		<category><![CDATA[Debug]]></category>
		<category><![CDATA[Delphi]]></category>

		<guid isPermaLink="false">http://delphitools.info/?p=433</guid>
		<description><![CDATA[A recurring subject when it comes to freeing objects and preventing is whether you should just .Free them, thus leaving a invalid reference that should however never be used anymore when the code design is correct, or if you should defensively FreeAndNil() them, thus leaving a nil value that will hopefully trigger AVs more often [...]]]></description>
			<content:encoded><![CDATA[<p>A recurring subject when it comes to freeing objects and preventing is whether you should just .Free them, thus leaving a invalid reference that should however never be used anymore when the code design is correct, or if you should defensively FreeAndNil() them, thus leaving a nil value that will hopefully trigger AVs more often on improper usage after release.</p>
<p>Allen Bauer recently brought this subject in his blog &#8220;<a href="http://www.delphifeeds.com/postings/65203-a_case_against_freeandnil">A case against FreeAndNil</a>&#8220;, arguing that there are better tools than FreeAndNil to diagnose improper usage after release, and that it can hide other issues and lead to other magic bullet solutions, which only further the problem. This is true, and FastMM debug mode can do wonders here, however, quite often, you don&#8217;t want to rely on a debug and diagnostic machinery that needs to be switched ON for problems to be detected early on.</p>
<p>Well, if you&#8217;re using FreeAndNil() for defensive purposes, don&#8217;t abuse it anymore, invest in a few lines of code for a shiny new FreeAndInvalidate():</p>
<pre>procedure FreeAndInvalidate(var obj);
var
   temp : TObject;
begin
   temp := TObject(obj);
   Pointer(obj) := Pointer(1);
   temp.Free;
end;
</pre>
<p>This function frees the object and sets the reference to an invalid magic value, which will trigger and AV on improper field or virtual method access after release  (just like FreeAndNil), but unlike FreeAndNil, it will also AV on multiple .Free attempt, and will not be stopped by &#8220;if Assigned()&#8221; checks. If you wish even more defense, you can also &#8220;sabotage&#8221; the VMT pointer of the freed object instance.</p>
<p>With a FreeAndInvalidate() added to your bag of tricks, you can now reserve FreeAndNil usage to situations where having a nil reference is truly part of the design, and no longer abuse it for defensive programming. Of course <em>this is still no magic-bullet, but it&#8217;s cheap enough that you can use it in release builds</em> (unlike debug and diagnostic tools), and as a bonus, it makes it obvious when reading the code that the object reference is supposed to be invalid after the call.</p>
]]></content:encoded>
			<wfw:commentRss>http://delphitools.info/2010/02/06/dont-abuse-freeandnil-anymore/feed/</wfw:commentRss>
		<slash:comments>7</slash:comments>
		</item>
		<item>
		<title>ZJDBGPack re-release</title>
		<link>http://delphitools.info/2009/05/04/zjdbgpack-re-release/</link>
		<comments>http://delphitools.info/2009/05/04/zjdbgpack-re-release/#comments</comments>
		<pubDate>Mon, 04 May 2009 08:35:42 +0000</pubDate>
		<dc:creator>Eric</dc:creator>
				<category><![CDATA[News]]></category>
		<category><![CDATA[Command]]></category>
		<category><![CDATA[Debug]]></category>
		<category><![CDATA[Delphi]]></category>
		<category><![CDATA[Download]]></category>
		<category><![CDATA[JCL]]></category>
		<category><![CDATA[Profiler]]></category>
		<category><![CDATA[Size]]></category>
		<category><![CDATA[ZJDBGPack]]></category>

		<guid isPermaLink="false">http://delphitools.info/?p=376</guid>
		<description><![CDATA[ZJDBGPack is again available, but as an independent download (it used to be bundled with SamplingProfiler). This is a command-line utility intended for use in a build process or from the Delphi tools menu, whose purpose is to integrate debug information into an executable. The debug information format  is a compressed version of JCL&#8216;s JDBG. [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://delphitools.info/other-tools/zjdbgpack/">ZJDBGPack</a> is again available, but as an independent download (it used to be bundled with SamplingProfiler).</p>
<p>This is a command-line utility intended for use in a build process or from the Delphi tools menu, whose purpose is to integrate debug information into an executable. The debug information format  is a compressed version of <a href="http://jcl.delphi-jedi.org/">JCL</a>&#8216;s JDBG.</p>
<p>As of know, <a href="http://delphitools.info/samplingprofiler/">SamplingProfiler</a> is the only published utility that understands this format, so you can use it either to reduce the size of the executables you deploy for profiling purposes, or if you do not want to deploy directly-readable debug information files.</p>
]]></content:encoded>
			<wfw:commentRss>http://delphitools.info/2009/05/04/zjdbgpack-re-release/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
