:: KBs ::

String.Concat vs StringBuilder

Created Date: 4/23/2008
Last Modified Date: 4/23/2008
Using the base string concatenation versus using string builder to concatenate strings is often a highly debated topic.

First, what advantages does a StringBuilder offer over the standard string concatenation? A StringBuilder is essentially an advanced data structure designed to link strings together faster. In .Net, the overall idea of it is to take string characters and add them to specific locations within the string’s character array. This can be done currently through the String class AppendInPlace method. If the string has available space less than the size of the array then the string is doubled in size over what the total length will be after appending.

All of this space doubling can provide a problem in non-memory rich environments such as Pocket PCs, cell phones, or even computers that are highly tapped on space. In these occurrences the String.Concat can be a better choice.

After testing the String.Concat vs the StringBuilder a couple of items popped out. The StringBuilder has a much larger build time than the String.Concat. When placing only 1 item to concatenate it took 2.5 times as long to instantiate the object. This general trend was seen for concatenating data all the way through 4 items. However, the StringBuilder became faster as soon as 5 items were to be concatenated together. This is due to the String.Concat only having overloads for up to 4 items. At that point the compiler has to perform multiple concatenations in order to get the same effect.



























Concat Builder
1 0.046878 0.109382
3 0.031252 0.07813
4 0.046878 0.07813
5 0.109382 0.093756
:: Better Coding Practices :: Inside the Compiler ::