Dot Net Perls

StringWriter Use With StringBuilder Buffer - C#

by Sam Allen

Problem

Write to the buffer of a StringWriter object using its internal StringBuilder, improving performance over converting method return values to string types. Our example combines HtmlTextWriter, the StringWriter object, and of course StringBuilder.

Solution: C#

StringWriter is implemented with an internal StringBuilder, making for excellent performance in most scenarios involving looping. For compatibility, we can use the internal buffer of the StringWriter directly. This means we can append to the buffer one piece at a time.

StringWriter example code

The major use of StringWriter in my experience is with HtmlTextWriter, but it can be used elsewhere too. (In my examples, the key point is how we access the StringBuilder from the writer, which is unrelated to the HtmlTextWriter.) Here is the example code.

class Example
{
    string[] _someStringArray = { "One", "Two" };

    public string GetMarkup()
    {
        StringWriter stringWriter = new StringWriter();
        using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
        {
            foreach (string item in this._someStringArray)
            {
                writer.RenderBeginTag(HtmlTextWriterTag.Div);

                // Send internal StringBuilder to markup method.
                WriteMarkup(item, stringWriter.GetStringBuilder());

                writer.RenderEndTag();
            }
        }
        return stringWriter.ToString();
    }

    private void WriteMarkup(string sourceString, StringBuilder builder)
    {
        // Writes the markup.
        builder.Append("Some").Append(" text");
    }
}
  1. New StringWriter declared
    In the above example, we declare a new StringWriter. This always has an internal StringBuilder. We use this for the HtmlTextWriter mainly. The HTML is written to the StringBuilder by HtmlTextWriter.
  2. GetStringBuilder() is called
    Look at how the stringWriter.GetStringBuilder() method is used to pass a reference to the WriteMarkup method. StringBuilder is much more common than StringWriter. This can greatly improve compatibility.
  3. No string overhead
    The WriteMarkup method could return a new string containing its results, but this would be very inefficient and non-ideal. It is best to reuse buffers and write one piece at a time. [C# - StringBuilder Mistake - dotnetperls.com]

StringBuilder used with GetStringBuilder

I have written about how using StringBuilder as a parameter is an excellent approach. The approach presented in this article is an extension of that. Passing StringBuilder with GetStringBuilder() is still an excellent idea. [C# - StringBuilder Secrets - dotnetperls.com]

Discussion

When working with a buffer or StringBuilder, always write new content to the same buffer. Don't create temporary strings and write those. This is an important principle in string handling. HtmlTextWriter here is used to make the HTML less bug-prone, but a StringBuilder-only approach would be faster.

Dot Net Perls
About
Sitemap
Source code
RSS
StringBuilder
StringBuilder Secrets
StringWriter Use With StringBuilder Buffer
StringBuilder Mistake and Benchmark
StringBuilder Performance Test
StringBuilder Append Syntax
Recent
Pi
NGEN Installer Class
List Element Equality
DateTime Tips and Tricks
Remove HTML Tags From String
© 2008 Sam Allen. All rights reserved.