The most efficient way to return string concatenation from a property

I read a few posts here, and the general suggestion is that a string collector is most efficient if it concatenates three strings.

all variables are other properties.

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

Im connecting four is simple concatenation, suitable or should I use stringbuilder? It just seems a bit crowded.

+4
source share
2 answers

Use what is most readable in this case. Otherwise, it is 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 so bad as strings are stored in the user pool . Therefore, if you use the string a second time, it is not created, but the existing link is used.

So, as a rule of thumb:

  • If you are concatenating multiple lines and the code is unlikely to parse, use String.Format
  • If you are concatenating multiple (literal) lines and the code is still being read, use + (string concatenation)
  • If you are creating strings in a long loop with variable strings, use StringBuilder
+8
source

Use String.Format

 public string Summary { get { return String.Format( "{0}<strong>[{1} Devices - {2} Offline, {3} Pending </strong>", Name.Replace("_", " "), Total, BadCount, PendingCount); } } 
+2
source

All Articles