I understand that StringBuilder
is the choice for concatenating strings in a loop, like this:
List<string> myListOfString = GetStringsFromDatabase();
var theStringBuilder = new StringBuilder();
foreach(string myString in myListOfString)
{
theStringBuilder.Append(myString);
}
var result = theStringBuilder.ToString();
But what are the scenarios where StringBuilder
outperforms String.Join()
or vice versa?
var theStringBuilder = new StringBuilder();
theStringBuilder.Append("Is this ");
theStringBuilder.Append("ever a good ");
theStringBuilder.Append("idea?");
var result = theStringBuilder.ToString();
OR
string result = String.Join(" ", new String[]
{
"Or", "is", "this", "a", "better", "solution", "?"
});
Any guidance would be greatly appreciated.
EDIT: Is there a threshold where the creation overhead of the StringBuilder
is not worth it?