Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most efficient way to return string concatenation from property

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.

like image 366
DavidB Avatar asked Dec 26 '22 10:12

DavidB


1 Answers

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
like image 89
Tim Schmelter Avatar answered Jan 17 '23 18:01

Tim Schmelter