Improving ASP.NET Performance Part 13: String Management

In our last article in the ASP.NET series we discussed View State Management in ASP. In this article we’ll address the best practices for String Management.

When providing output, you often need to concatenate strings, which is an expensive operation because it requires temporary memory allocation and subsequent collection. As a result, you should minimize the amount of string concatenation that you perform. There are three common ways to concatenate strings in your pages to render data:

·         Using the += operator. Use the += operator when the number of appends is known.

·         StringBuilder. Use the StringBuilder object when the number of appends is unknown. Treat StringBuffer as a reusable buffer.

·         Response.Write <% %>. Use the Response.Write method. It is one of the fastest ways to return output back to the browser.

The most effective way to determine the option to choose is to measure the performance of each option. If your application relies heavily on temporary buffers, consider implementing a reusable buffer pool of character arrays or byte arrays.

Best Practices and Guidelines

Use Response.Write for Formatting Output

Where possible, avoid using loops to concatenate strings for formatting page layout. Consider using Response.Write instead. This approach writes output to the ASP.NET response buffers. When you are looping through datasets or XML documents, using Response.Write is a highly efficient approach. It is more efficient than concatenating the content by using the += operator before writing the content back to the client. Response.Write internally appends strings to a reusable buffer so that it does not suffer the performance overhead of allocating memory, in addition to cleaning that memory up.

Use StringBuilder for Temporary Buffers

In many cases it is not feasible to use Response.Write. For example, you might need to create strings to write to a log file or to build XML documents. In these situations, use a StringBuilder object as a temporary buffer to hold your data. Measure the performance of your scenario by trying various initial capacity settings for the StringBuilder object.

Use HtmlTextWriter When Building Custom Controls

When you are building custom controls, the Render, RenderChildren, and RenderControl methods provide access to the HtmlTextWriter object. The HtmlTextWriter writes to the same reusable buffer as Response.Write. In the same way as Response.Write, HtmlTextWriter does not suffer the performance overhead of allocating memory in addition to cleaning up the memory.

In our next article we’ll discuss best practices for Exception Management.