Karl Anderson
Karl Anderson

Reputation: 34846

Is StringBuilder only preferred in looping scenarios?

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?

Upvotes: 3

Views: 217

Answers (3)

cuongle
cuongle

Reputation: 75296

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.

Upvotes: 5

tmaj
tmaj

Reputation: 34947

StringBuilder will outperform string operations in most scenarios when it comes to memory usage.

I routinely use StringBuilder to build full logging information as I need to join pieces of information from multiple sources.

Jeff Atwood's The Sad Tragedy of Micro-Optimization Theater could be is a good read too.

Upvotes: -1

nhrobin
nhrobin

Reputation: 903

String.Join has several overloads. Some of them takes string[] and other takes IEnumerable<string>. If you see the source code of them you will notice that they are implemented differently.

For array case String.Join first calculate the total number of characters then allocate a string of that size.

But for IEnumarable case it just use StringBuilder.Append inside.

So if you have array of string then probably String.Join is faster than StringBuilder.Append but for IEnumarable case performance is same.

For all cases I will suggest to use String.Join as it requires less code.

Upvotes: 1

Related Questions