.NET: string concatenation drama

I have previously mentioned about string.Format() in .NET. But I had to come back to this older-than-steve-ballmer issue just to mark it down in my blog: why there are people using string.Format() or StringBuilder to concatenate strings rather than using the “+” operator? I even bother to spend time writing this down because it’s been raised too many times in many chit chats from time to time.

Today I had people talking about why there are server code like string.Format("My name is: {0}", "Leon") instead of "My name is: " + "Leon".

Ok, if not for readability or formatting purpose, String.Format is considered a bad practice. You should always use “+” concatenation for single statement operation, StringBuilder for multi-statement operation in server code.

Single-statement is like:

string s = "My " + "name " + "is " + "Leon.";

Multi-statement is like:

string s = "My ";
s += "name ";
s+= "is ";
s+= "Leon.";

String objects in .NET are immutable. Once the string has been created, the value can’t be changed. When you type s += "Leon", you actually discard the old s and create a new string object containing the result of the concatenation. When repeated several times, you end up constructing many temporary string objects and this can kill your server for high memory consumption. In the single statement example, 1 string instances are created which is the concatenation result. In the multi-statement example, 4 instances are created because the string has been modified 4 times.

StringBuilder is created especially for concatenating strings in the multi-statement case. It uses a special mechanism to prevent multiple string instances while still allowing you to concatenate more strings using the Append function.

For details on this topic, I suggest taking a look at this detailed analysis.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s