Is StringBuilder only preferred in looping scenarios?

c#, stringbuilder

Solution

It seems `string.Join` uses `StringBuilder` under the hood from the code (Reflector):

public static string Join(string separator, IEnumerable<string> values)
{
    using (IEnumerator<string> enumerator = values.GetEnumerator())
    {
        if (!enumerator.MoveNext())
        {
            return Empty;
        }
        StringBuilder sb = StringBuilderCache.Acquire(0x10);
        if (enumerator.Current != null)
        {
            sb.Append(enumerator.Current);
        }
        while (enumerator.MoveNext())
        {
            sb.Append(separator);
            if (enumerator.Current != null)
            {
                sb.Append(enumerator.Current);
            }
        }
        return StringBuilderCache.GetStringAndRelease(sb);
    }
}

So in your scenario, it does not different much. But I would prefer using `StringBuilder` when trying to concat string based on the conditions.

Problem

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?

Original source

Related problems