Thursday 15 January 2015

ASP.NET Tips #16 - Use StringBuilder or String.Join for string concatenation?

If you are in a loop and adding to a string, then a StringBuilder *could* be most appropriate. However, the overhead of spinning up a StringBuilder instance makes the following pretty dumb:

   var sb = new StringBuilder();
   sb.Append("Frankly, this is ");
   sb.Append(notMoreEfficient);
   sb.Append(". Even if you are in a loop.");
   var whyNotJustConcat = sb.ToString();

Instead, use String.Join, which is typically more effective than spinning up a StringBuilder instance for a limited number of strings.

   string key = String.Join(" ", new String[] { "This", "is", "a", "much", "better", solution, "."});

The first variable of " " can just be set to "" when you don't want a delimiter.

My rule of thumb is to add strings together when got one to five of them (likewise with String.Form if it helps with legibility). For most other cases, I tend to use String.Join. Only when dealing with a loop that isn't limited to about 10 iterations, I prefer to use StringBuilder.

No comments :

Post a Comment