Wednesday, June 18, 2008

Examining the StringBuilder Class

I don't know what it was, perhaps sheer boredom or perhaps the desire to explore, but I set out to examine the StringBuilder in .NET today. A StringBuilder is used when you need performance with modifying strings within your application. The performance comes from the dynamic extension of the string, rather than creating a new string object each time a modification is made. This behavior is due to immutable nature of the .NET string.

Running a performance test to compare the string class with the StringBuilder class gives the following results:

For 100,000 iterations of appending strings:
StringBuilder: 16 ms
String: 16,000 ms

For 110,000 iterations of appending strings:
StringBuilder: 16 ms
String: 19,640 ms

For 150,000 iterations of appending strings:
StringBuilder: 16 ms
String: 37,953 ms

For 180,000 iterations of appending strings:
StringBuilder: 16 ms
String: 55,687 ms

For 200,000 iterations of appending strings:
StringBuilder: 32 ms
String: 69,047 ms

The time required for appending strings using the .NET String class increases for an increasing number of iterations. However, the time for the StringBuilder class seems to remain constant for a certain range of iterations and then increases for the next range.

The behavior of the StringBuilder results from allocation of memory in a chunk, rather than allocation of additional memory for each append operation. A closer look at the source code of the StringBuilder using the Lutz Roeder Reflector gives an insight into how memory is allocated. Take a look at the following code:


int capacity = currentString.Capacity * 2;
if (capacity < requiredLength)
{
capacity = requiredLength;
}
if (capacity > maxCapacity)
{
capacity = maxCapacity;
}


A StringBuilder is usually extended to twice it's size. If this length is insufficient, it extends to the required size. However, it does not exceed the maximum capacity specified for the StringBuilder. This approach seems to work fine - the number of memory allocations reduce over time when a fixed-length string is appended to the string builder.

No comments: