10

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 :)

David Rogers
  • 2,601
  • 4
  • 39
  • 84
Robbie Tapping
  • 2,516
  • 1
  • 17
  • 18
  • Possible duplicate: http://stackoverflow.com/questions/3069416/difference-between-string-and-stringbuilder-in-c, http://stackoverflow.com/questions/73883/string-vs-stringbuilder – kevindaub Feb 27 '11 at 01:41
  • 1
    It is exactly the opposite of what you think. Measure first, make your argument from facts instead of guesses. Use the Stopwatch class. – Hans Passant Feb 27 '11 at 01:41
  • 2
    @Hans what do you mean by your comment, I'm asking a question on advice from the wider community rather than my personal checking. I have no argument, i have a question. So im asking you for the facts. – Robbie Tapping Feb 27 '11 at 01:44
  • 1
    instead of convincing them to use string.Format or StringBuilder you should try to convince them to use parameters when building SQL statements. – juharr Feb 27 '11 at 02:20
  • 1
    **There is absolutely *nothing* wrong with your first snippet of code.** Replacing it with `String.Format` is a useless optimization. You should generally be suspicious of people who make absolute statements like "never do x". You won't lose performance, because the compiler will replace it with a call to `String.Concat` which is *remarkably* fast. And you only need `StringBuilder` if you're doing string concatenation *in a loop*; a good rule of thumb is more than 5 concatenations, refactor it to use a `StringBuilder` rather than `+`. For two additions, it's not worth the time to optimize. – Cody Gray - on strike Feb 27 '11 at 10:23
  • 1
    There's actually another reason you'd want to avoid concatenation with +, but it has more to do with maintainability than performance. if your must calculate the string in multiple places, it's easier to maintain a single format string than change multiple string concats. Then you can just feed your format string and your data into a String.Format, which is much nicer (though I'm not sure what the performance is like) – Benjamin Sep 04 '14 at 08:35

3 Answers3

6

StringBuilder is really only useful in a performance sense when you are building a very large string which requires a lot of concatenation. For the small samples you provided I think that using the + operator is just fine.

When it comes to String.Format, I think it should be used to improve the readability or flexibility of the code but not really for performance reasons. String.Format also has the added benefit of supporting localization which is not really easy when using the + operator.

I have never run into a situation in my experience where concatenation was causing a serious perf problem so I always choose the most readable code before trying to optimize for performance.

Luke Foust
  • 2,234
  • 5
  • 29
  • 36
  • If you edit this answer to include the internationalisability benefit of string.Format, I’ll upvote it. – Timwi Feb 27 '11 at 01:41
6

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

Cosmin
  • 2,365
  • 2
  • 23
  • 29
1

I know that Java actually optimizes the +'s in one line to a statement using StringBuffer (Java's version of StringBuilder), so I guess C# probably does the same. Therefore it shouldn't really make a difference. Only if that one line is the most executed line in your program, it would be really worth looking at the difference (assuming it exists).

However, when you build an entire page using += statements instead of using a StringBuilderthe difference is quite noticeable ;) I once rewrote a ASP.NET C# page which actually both build up the (large) SQL queries as the entire response using += instead of StringBuilders. I got the loadtime down from 20 secs to <1 sec ;) So yes, do try to avoid += to build strings.

markijbema
  • 3,985
  • 20
  • 32
  • 3
    The C# compiler optimises a series of string concatenations in one statement using multiple `+`'s to a single `String.Concat(...)` which uses direct memory access techniques to perform much faster copying. – Callum Rogers Feb 27 '11 at 01:47