Search code examples
c#stringstringbuilder

String Format and Building Strings with "+"


I want to ask what peoples thoughts are about writing strings and if there is a massive difference on performance when building a string.

I have always been told in recent years to never do the following:

string dogName = "Ralph";
DateTime bornDate = DateTime.Parse("2010-01-01");

string fullText = "I am a Dog and my name is " + dogName + " and i was born on the " + bornDate.ToString("dd/MM/yyyy");

And always told to something similar as below.

string dogName = "Ralph";
DateTime bornDate = DateTime.Parse("2010-01-01");

string fullText2 = String.Format("I am a Dog and my name is {0} and i was born on the {1:dd/MM/yyyy}", dogName, bornDate);

I see the reason for using the later statement, but does anyone know what type of performance issues there are with the first one.

And with the StringBuilder Object instead of using

string str = "Adding this comment to the string\n"
str += "Then Add this line";

and using the following:

StringBuilder sb = new StringBuilder();

sb.AppendLine("Add This Comment");
sb.AppendLine("Then add this comment");

string output = sb.ToString();

I have a handful of developers in my team at work that are a bit old school VB6 programmers and i want to explain to them why it a bad idea.

They do the Initial code example constantly for In Code SQL Statements.

If it is of course :)


Solution

  • The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.

    Source: http://msdn.microsoft.com/en-us/library/system.text.stringbuilder.aspx