<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	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/"
		>
<channel>
	<title>Comments on: Three Ways to Clear a StringBuilder</title>
	<atom:link href="http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/feed/" rel="self" type="application/rss+xml" />
	<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/</link>
	<description>Musings on the craft and business of software development</description>
	<lastBuildDate>Thu, 10 Jun 2010 13:45:33 -0600</lastBuildDate>
	<generator>http://wordpress.org/?v=2.8.6</generator>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
		<item>
		<title>By: James Radford, Web Developer</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-9552</link>
		<dc:creator>James Radford, Web Developer</dc:creator>
		<pubDate>Tue, 08 Jun 2010 14:09:08 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-9552</guid>
		<description>thanks for the post..  Is this not okay?  

StringBuilder sb = new StringBuilder();
sb.Append(&quot;hello&quot;);
sb = new StringBuilder();

&lt;em&gt;Bob responds:
Presumably newing up another instance is more expensive than simply clearing the buffer of an existing one.  Also, creating new instances and abandoning old ones probably means more memory fragmentation and would tend to run the garbage collector more.  Can&#039;t say that I&#039;ve tested it, though, and one&#039;s mileage would vary depending on usage patterns.  Always remember, most of this discussion ends up not mattering all that much in terms of performance unless you&#039;re in a tight loop with many iterations, and then, of course, it&#039;s best to verify your assumptions with testing.&lt;/em&gt;</description>
		<content:encoded><![CDATA[<p>thanks for the post..  Is this not okay?  </p>
<p>StringBuilder sb = new StringBuilder();<br />
sb.Append(&#8221;hello&#8221;);<br />
sb = new StringBuilder();</p>
<p><em>Bob responds:<br />
Presumably newing up another instance is more expensive than simply clearing the buffer of an existing one.  Also, creating new instances and abandoning old ones probably means more memory fragmentation and would tend to run the garbage collector more.  Can&#8217;t say that I&#8217;ve tested it, though, and one&#8217;s mileage would vary depending on usage patterns.  Always remember, most of this discussion ends up not mattering all that much in terms of performance unless you&#8217;re in a tight loop with many iterations, and then, of course, it&#8217;s best to verify your assumptions with testing.</em></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: nemo</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-9457</link>
		<dc:creator>nemo</dc:creator>
		<pubDate>Tue, 08 Dec 2009 17:59:10 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-9457</guid>
		<description>Nice tips! 

To expand it even further, in .NET 3.5 (not sure which version it was introduced) you can create an expanded method as such:

		public static void Clear(this StringBuilder stringBuilder)
		{
			stringBuilder.Length = 0;
			stringBuilder.Capacity = 16;
		}

now when you create your stringbuilder you can call it normally.  For example:
  StringBuilder sb = new StringBuilder();
  sb.Clear();

&lt;em&gt;Bob responds:

Thanks, excellent point.  Depending on the reuse pattern, resetting Capacity back to the default of 16 bytes may or may not be desirable, because re-expanding capacity is expensive.  It may make sense to leave it alone, or set it to a larger value than 16.  So my impulse would be to default to leaving it be, and taking an optional argument to set it to a specific value.

To this end -- 3.5 introduces a Clear() method anyway, and while it&#039;s not documented what, if anything it does to the Capacity value, if it leaves it alone, creating an extension method that sets it to a specific value might be a useful enhancement.
&lt;/em&gt;</description>
		<content:encoded><![CDATA[<p>Nice tips! </p>
<p>To expand it even further, in .NET 3.5 (not sure which version it was introduced) you can create an expanded method as such:</p>
<p>		public static void Clear(this StringBuilder stringBuilder)<br />
		{<br />
			stringBuilder.Length = 0;<br />
			stringBuilder.Capacity = 16;<br />
		}</p>
<p>now when you create your stringbuilder you can call it normally.  For example:<br />
  StringBuilder sb = new StringBuilder();<br />
  sb.Clear();</p>
<p><em>Bob responds:</p>
<p>Thanks, excellent point.  Depending on the reuse pattern, resetting Capacity back to the default of 16 bytes may or may not be desirable, because re-expanding capacity is expensive.  It may make sense to leave it alone, or set it to a larger value than 16.  So my impulse would be to default to leaving it be, and taking an optional argument to set it to a specific value.</p>
<p>To this end &#8212; 3.5 introduces a Clear() method anyway, and while it&#8217;s not documented what, if anything it does to the Capacity value, if it leaves it alone, creating an extension method that sets it to a specific value might be a useful enhancement.<br />
</em></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: turdy</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-9403</link>
		<dc:creator>turdy</dc:creator>
		<pubDate>Wed, 18 Nov 2009 14:50:54 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-9403</guid>
		<description>Lovely tip thanks</description>
		<content:encoded><![CDATA[<p>Lovely tip thanks</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: William</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-7307</link>
		<dc:creator>William</dc:creator>
		<pubDate>Wed, 12 Nov 2008 22:38:13 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-7307</guid>
		<description>One last thing:

Just because it&#039;s small doesn&#039;t mean it doesn&#039;t matter (or at least that&#039;s what my gf tells me).

If you save 16 bytes or 2MB, it may seem small until you multiply it by the number of users. 

Consider the user count of say Mysp@ce or M$ or the NY Stock Exchange.

&lt;em&gt;Bob responds: There is a balance between thrashing and a stable state to consider.  I am simply saying that with a single StringBuilder, if you expect to construct strings of say 50 to 100 bytes, with the majority toward the top end, set an initial capacity of 100 and leave it alone.  Destroy the StringBuilder when you are done with it.  This is better and simpler in almost all real world cases than tamping the capacity back down, unless actual testing reveals a clear advantage, which I predict it won&#039;t.&lt;/em&gt;</description>
		<content:encoded><![CDATA[<p>One last thing:</p>
<p>Just because it&#8217;s small doesn&#8217;t mean it doesn&#8217;t matter (or at least that&#8217;s what my gf tells me).</p>
<p>If you save 16 bytes or 2MB, it may seem small until you multiply it by the number of users. </p>
<p>Consider the user count of say Mysp@ce or M$ or the NY Stock Exchange.</p>
<p><em>Bob responds: There is a balance between thrashing and a stable state to consider.  I am simply saying that with a single StringBuilder, if you expect to construct strings of say 50 to 100 bytes, with the majority toward the top end, set an initial capacity of 100 and leave it alone.  Destroy the StringBuilder when you are done with it.  This is better and simpler in almost all real world cases than tamping the capacity back down, unless actual testing reveals a clear advantage, which I predict it won&#8217;t.</em></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: William</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-7306</link>
		<dc:creator>William</dc:creator>
		<pubDate>Wed, 12 Nov 2008 22:35:02 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-7306</guid>
		<description>Just did a little experiment and:

someStringBuilder.length = 0 ; 

does not reduce the capacity as expected. 

If using .net 2.0 follow your &#039;length = 0 &#039; with .capacity = 0;
like this:

someStringBuilder.length = 0;
someStringBuilder.capacity = 0;

Together Everyone Achieves More

&lt;em&gt;Bob responds: Yes, length and capacity are two separate issues.  The default initial capacity is 16, the default initial length is zero.  The string grows until it reaches the capacity and triggers an expansion.  So if your objective is to reduce the buffer size you have to set capacity separately.  However I would never set the capacity to zero.  That guarantees that on future Append() calls you will have at least one auto-expansion of the buffer -- an expensive and potentially memory-fragmenting operation.  Zero should not be a legal value for Capacity.  Set Capacity to at least 1 or the minimum length of the string you expect to create, whichever is larger.&lt;/em&gt;</description>
		<content:encoded><![CDATA[<p>Just did a little experiment and:</p>
<p>someStringBuilder.length = 0 ; </p>
<p>does not reduce the capacity as expected. </p>
<p>If using .net 2.0 follow your &#8216;length = 0 &#8216; with .capacity = 0;<br />
like this:</p>
<p>someStringBuilder.length = 0;<br />
someStringBuilder.capacity = 0;</p>
<p>Together Everyone Achieves More</p>
<p><em>Bob responds: Yes, length and capacity are two separate issues.  The default initial capacity is 16, the default initial length is zero.  The string grows until it reaches the capacity and triggers an expansion.  So if your objective is to reduce the buffer size you have to set capacity separately.  However I would never set the capacity to zero.  That guarantees that on future Append() calls you will have at least one auto-expansion of the buffer &#8212; an expensive and potentially memory-fragmenting operation.  Zero should not be a legal value for Capacity.  Set Capacity to at least 1 or the minimum length of the string you expect to create, whichever is larger.</em></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: William</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-7305</link>
		<dc:creator>William</dc:creator>
		<pubDate>Wed, 12 Nov 2008 22:24:44 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-7305</guid>
		<description>You should check garbage collection because it starts with a small size and gets bigger as you append to it. If you clear it and don&#039;t check the size it uses this could be a performance hit on small machines like CE and others.

M$ says in article on MSDN:
Notes to Implementers: 
The default capacity for this implementation is 16, and the default maximum capacity is Int32..::.MaxValue. 

http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx

&lt;em&gt;Bob responds: In general, you will clear the buffer in order to re-use the StringBuilder, likely to construct another string of similar size.  Nothing is to be gained by shrinking and re-growing the capacity (re-expansion is expensive too) unless you won&#039;t be using the StringBuilder at all, in which case the entire StringBuilder should go out of scope anyway.  In addition, garbage collection is non-deterministic and you have only rough control over it.  If you must obsess over managing a system that is carefully designed and tuned to manage itself just fine in the vast majority of real-world scenarios, your concern is likely misplaced.  You should be more concerned about the design of your object graph.  Finally keep in mind that you can very often set the initial capacity when the StringBuilder is constructed.  You can set the capacity for the expected use in such a way that the buffer will auto-expand very little if at all during use, thus minimizing memory fragmentation.&lt;/em&gt;</description>
		<content:encoded><![CDATA[<p>You should check garbage collection because it starts with a small size and gets bigger as you append to it. If you clear it and don&#8217;t check the size it uses this could be a performance hit on small machines like CE and others.</p>
<p>M$ says in article on MSDN:<br />
Notes to Implementers:<br />
The default capacity for this implementation is 16, and the default maximum capacity is Int32..::.MaxValue. </p>
<p><a href="http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx" rel="nofollow">http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx</a></p>
<p><em>Bob responds: In general, you will clear the buffer in order to re-use the StringBuilder, likely to construct another string of similar size.  Nothing is to be gained by shrinking and re-growing the capacity (re-expansion is expensive too) unless you won&#8217;t be using the StringBuilder at all, in which case the entire StringBuilder should go out of scope anyway.  In addition, garbage collection is non-deterministic and you have only rough control over it.  If you must obsess over managing a system that is carefully designed and tuned to manage itself just fine in the vast majority of real-world scenarios, your concern is likely misplaced.  You should be more concerned about the design of your object graph.  Finally keep in mind that you can very often set the initial capacity when the StringBuilder is constructed.  You can set the capacity for the expected use in such a way that the buffer will auto-expand very little if at all during use, thus minimizing memory fragmentation.</em></p>
]]></content:encoded>
	</item>
	<item>
		<title>By: slade73</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-6418</link>
		<dc:creator>slade73</dc:creator>
		<pubDate>Thu, 21 Aug 2008 20:34:35 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-6418</guid>
		<description>Thanks for the tip! I too have always found it odd that there&#039;s no Clear() method, and even though setting the Length property to zero accomplishes the same thing, I&#039;d have still included a Clear() method for clairity/consistency. :)

Thanks again!</description>
		<content:encoded><![CDATA[<p>Thanks for the tip! I too have always found it odd that there&#8217;s no Clear() method, and even though setting the Length property to zero accomplishes the same thing, I&#8217;d have still included a Clear() method for clairity/consistency. :)</p>
<p>Thanks again!</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Marcelo Lopez</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-5996</link>
		<dc:creator>Marcelo Lopez</dc:creator>
		<pubDate>Thu, 24 Jul 2008 19:33:52 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-5996</guid>
		<description>Ahmed ....where ? I don&#039;t see .Clear() coming up in a newly created solution in VS2008 using 3.5.  What assembly/version are you loading that includes that interface for StringBuilder ?</description>
		<content:encoded><![CDATA[<p>Ahmed &#8230;.where ? I don&#8217;t see .Clear() coming up in a newly created solution in VS2008 using 3.5.  What assembly/version are you loading that includes that interface for StringBuilder ?</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: Ahmed</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-4189</link>
		<dc:creator>Ahmed</dc:creator>
		<pubDate>Wed, 27 Feb 2008 18:40:01 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-4189</guid>
		<description>FYI, .NET 3.5 framework introduces StringBuilder.Clear()</description>
		<content:encoded><![CDATA[<p>FYI, .NET 3.5 framework introduces StringBuilder.Clear()</p>
]]></content:encoded>
	</item>
	<item>
		<title>By: decebal</title>
		<link>http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/comment-page-1/#comment-2109</link>
		<dc:creator>decebal</dc:creator>
		<pubDate>Thu, 16 Aug 2007 14:23:08 +0000</pubDate>
		<guid isPermaLink="false">http://bobondevelopment.com/2007/06/11/three-ways-to-clear-a-stringbuilder/#comment-2109</guid>
		<description>Nice tip(s).
Did you check the memory after a garbage collection to see if it really saves anything?

&lt;em&gt;Bob responds: No, because the point isn&#039;t to save memory, it&#039;s to clear a string builder for re-use in a way that is simpler.  If you need to clear it, you need to clear it.  In addition, you beg the question, &quot;saves anything in comparison to what?&quot;  Saves time vs newing up a new StringBuilder?  Probably.  Saves time vs the other methods I mentioned?  Very likely.  Enough of either to matter?  Depends on the particular situation and the mix of factors such as how much other work is being done within the loop, the size of the strings being manipulated, and so on.  But I subscribe to the principle that the drop-dead simplest way of doing any one thing tends to be the very best way of doing that thing, even if the only obvious benefit is elegant, self-evident code.

If you mean, does setting the length to zero clear the buffer and free any memory ... I doubt it.  A StringBuilder has a default initial capacity of 16 byes (you can override the default with one of the overloaded constructors).  If the string exceeds the capacity, the internal buffer is doubled in size until it&#039;s big enough.  I&#039;m sure that setting the length to zero simply makes the buffer re-usable, and doesn&#039;t shrink it.  However, in most cases, freeing up memory would not be a net win because as the new string is built, the buffer would have to be re-expanded, which is a fairly expensive operation (and for all I know, tends to fragment memory).&lt;/em&gt;</description>
		<content:encoded><![CDATA[<p>Nice tip(s).<br />
Did you check the memory after a garbage collection to see if it really saves anything?</p>
<p><em>Bob responds: No, because the point isn&#8217;t to save memory, it&#8217;s to clear a string builder for re-use in a way that is simpler.  If you need to clear it, you need to clear it.  In addition, you beg the question, &#8220;saves anything in comparison to what?&#8221;  Saves time vs newing up a new StringBuilder?  Probably.  Saves time vs the other methods I mentioned?  Very likely.  Enough of either to matter?  Depends on the particular situation and the mix of factors such as how much other work is being done within the loop, the size of the strings being manipulated, and so on.  But I subscribe to the principle that the drop-dead simplest way of doing any one thing tends to be the very best way of doing that thing, even if the only obvious benefit is elegant, self-evident code.</p>
<p>If you mean, does setting the length to zero clear the buffer and free any memory &#8230; I doubt it.  A StringBuilder has a default initial capacity of 16 byes (you can override the default with one of the overloaded constructors).  If the string exceeds the capacity, the internal buffer is doubled in size until it&#8217;s big enough.  I&#8217;m sure that setting the length to zero simply makes the buffer re-usable, and doesn&#8217;t shrink it.  However, in most cases, freeing up memory would not be a net win because as the new string is built, the buffer would have to be re-expanded, which is a fairly expensive operation (and for all I know, tends to fragment memory).</em></p>
]]></content:encoded>
	</item>
</channel>
</rss>
