Tuesday, May 20, 2008

[C#] Efficient String Concatenation - "+=" vs StringBuilder

Again, in my short C# travels, I find myself very very often doing dynamic string concatenations. One major task I have tried to do is create a basic serialization function for XAML elements, so that I can store/save a XAML element to the server in my project. I thus end up doing many, many string concatenations.

Using "+=" to Concat
So often I end up doing this...:

String newStr = "";
if ([prop] != null) { newStr += "[prop]= " + obj.getValue([prop]).toString(); }

...for many, many properties. When actually compiled, every time the "+=" concatenation is used, an entirely new string must be created to hold the 'new' complete string. This can become very inefficient and slow if you do a large number of such string concats.


Using StringBuilder

What I didn't know about, was the StringBuilder class. Found under the System.Text library, StringBuilder maintains an internal buffer to which [via the function StringBuilder.Append()] will append to; thus a new string will not be created every time an append occurs. If the internal buffer is exceeded THEN a new buffer size will be allocated.

Thus the usage of StringBuilder *CAN* be more efficient then using "+=". Note that more overhead is needed to create and manage the StringBuilder object, so in all cases, StringBuilder will *NOT* be absolutely more efficient. It really depends on the size of the strings and the frequency of the concats.

General Rule of Thumb
  • If the concats can fit into one statement [or only a few statements], then the "+=" is probably the safest route to take.
  • If you have multiple long, or a dynamic amount of string concats, then StringBuilder may be able to increase efficiency.

Reference: www.yoda.archsys.com

No comments: