Sunday, January 20, 2008

 

String Concatentation

StringBuilder...StringBuilder...StringBuilder! We have have all heard that in C#.NET, programmers should use StringBuilder for string concetenation. Some initial testing I had done awhile back seemed to indicate that is not necessarily the case. If your cocatenation occurs within the same statement, then just using the + operator seemed to have better performance.


// String Concatenation Using + in one statement is effecient
string z = a + b + c + d + e; // You get the idea
 

But, if your concatenation occured across multiple lines of code or within each pass of a loop, then the StringBuilder seemed faster.


// String Builder should be used
StringBuilder sb = new StringBuilder();
for (int x = 0; x < 10; x++)
{
sb.Append(x);
}
string z = sb.ToString();
 

I was going to investigate this further and come up with some proof. But, I happened across the following excellent post on John's Performance Blog and I didn't think there was any need to reverse engineer the wheel again.

Comments: Post a Comment





<< Home

This page is powered by Blogger. Isn't yours?

Subscribe to Posts [Atom]