4

Ive read a few posts on here and the common suggestion is that stringbuilder is the most efficent if joining over three strings.

all variables are other properties.

public string Summary
{
  get 
  {
    return Name.Replace("_", " ") + "<strong>[" + Total + " Devices - " + BadCount + " Offline, " + PendingCount + " Pending]</strong>";
  }
}

Im joining four, is a simple concatenation suitable or should I ue stringbuilder? Just seems a little overkill.

Sebastian Krysmanski
  • 8,114
  • 10
  • 49
  • 91
DavidB
  • 2,566
  • 3
  • 33
  • 63

2 Answers2

8

Use whatever is most readable in this case. Otherwise it's premature optimization.

I would use String.Format:

String result = String.Format("{0}<strong>[{1} Devices - {2} Offline, {3} Pending]</strong>"
, Name.Replace("_", " ")
, Total
, BadCount
, PendingCount);
return result;

Even string concatenation is not that bad since strings are stored in the intern pool. So if you use a string a second time it's not created but the already available reference is used.

So as rule of thumb:

  • If you're concatenating few strings and the code gets hardly to understand, use String.Format
  • If you're concatenating few (literal) strings and the code is still readable, use +(string concatenation)
  • If you're creating strings in a (long) loop with variable strings, use a StringBuilder
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
  • 3
    Reminds me of this quote: 'You should be more worried about the maintainability and readability of your code than its performance.' The performance difference will be nearly non-existent in the example. – BBQ Jan 24 '13 at 09:53
  • Thanks for the answer, Ill use string format and accept your answer for the additonal info. – DavidB Jan 24 '13 at 11:04
2

Use String.Format

public string Summary
{
  get 
  {
    return String.Format(
        "{0}<strong>[{1} Devices - {2} Offline, {3} Pending </strong>",
        Name.Replace("_", " "), Total, BadCount, PendingCount);
  }
}
Mehmet Ataş
  • 11,081
  • 6
  • 51
  • 78
  • 4
    Why? Apart from tidiness, what performance advantage does it offer over concatenation? (Note this is not disputing your answer, you simply need to do better than say *"use string.Format()"*). – slugster Jan 24 '13 at 09:44
  • String.Format uses a `StringBuilder`. It might be neater, but I doubt it's faster. – Tim M. Jan 24 '13 at 09:45
  • 2
    Far and away the best approach. String.Format() is optimised, and it also allows you to easily provide localization by putting the format string into the resources. You should always do that anyways, even if you're not going to be localising stuff. – Matthew Watson Jan 24 '13 at 09:45
  • Excellent answer, this is the approach I will use. – DavidB Jan 24 '13 at 11:03