Thursday, March 24, 2005


Fastest way to replace contents in a StringBuilder

I was reviewing some .NET code for a new feature when I came across the following piece of code:

_sXML.Replace(_sXML.ToString(), newValue);

It took me a while to understand what the developer wanted to do. It replaces the entire contents of the _sXML StringBuilder with the new value. A creative, but slow way, to do replace the entire contents of a StringBuilder with the a value.

I told the developer that it would be a lot faster to set the length to 0 and then append the new contents but  I was curious to see the performance difference. I compared the following ways to do the same thing:

  1. builder.Replace(buffer.ToString(), newValue);  //1392 ms

  2. builder.Length=0; buffer.Append(newValue);  // 130 ms

  3. builder = new StringBuilder();  // 420 ms

The results make perfect sense. Setting the Length to 0 clears the contents of the StringBuilder but it does not release the buffer. Appending the new value is quick as it does not have to re-allocate a new buffer.

No comments:

Post a Comment