I’ve always been a little shady on the reason the StringBuilder class was created in dotnet. Obviously it has some advanced string formatting functionality which allow you to create complex composite strings easily, but what else does it provide. The answer to that question came to me when I was debugging our internal translation application written in C#.
We were receiving out of memory exceptions on and off from the app. After analyzing the code by hand for several hours I was still lacking an answer as to why this program swelled to 3 gigs of memory usage. It did store a massive size of string data in string classes, but since the database containing the strings was only 90 megs, it made no sense that string data would be the reason the program was eating memory.
However I had not taken one important thing into account, .Net strings are immutable, and in several places we we’re playing fun games with the strings values to properly format them to the output, calling string functions such as SubString and Trim liberaly. Turns out 2.7 gigs of memory we’re being used by all the intermediate string values as the string mutated to its final output.
The solution here was to use the StringBuilder class. After replacement memeory usage dropped down to 300 megs for the entire program, simply because we were not creating a bunch of invariant strings as we mutated our data.
Moral of the story, when handling string data that you expect to be changing alot in place, or strings that are quite hefty in size, StringBuilder is hands down a better solution, especially if memory use is a prime concern.Posted by David Lock on July 20th, 2007 under Uncategorized |