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.
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.
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");
}
}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]
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.