3

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?

Karl Anderson
  • 34,606
  • 12
  • 65
  • 80
  • 4
    http://stackoverflow.com/questions/585860/string-join-vs-stringbuilder-which-is-faster Similar post, not exactly the same – Dan Drews Aug 13 '13 at 03:20
  • All I know (which was acknowleged in the question) is that stringbuilder blows concatenation out of the water (Cut one scheduled task of mine from about 3 hours to 5 minutes) – Dan Drews Aug 13 '13 at 03:24
  • @DanDrews what the hell task were you doing?! – Jonesopolis Aug 13 '13 at 03:26
  • @Jonesy: Heavy looping, probably. – SLaks Aug 13 '13 at 03:28
  • @Jonesy I was parsing lots of XML from a DB and because of this http://support.microsoft.com/kb/310378 I had to loop through thousands of rows (because they were huge XML files) to concatenate them into one large string. I had been using concatenation rather than StringBuilder and I repeat this 30 times for the task Unfortunately, we have a framework setup that I had to use so I couldn't use execute XML reader, but switching to stringbuilder made it quick enough – Dan Drews Aug 13 '13 at 03:29
  • Rule of thumb for me is, if there's a framework method that does the job, use that as it'll invariably be optimized for the scenario (using a SB internally or pre-allocating a string etc.). In this case, Join fits your criteria so I'd run with it. – Plymouth223 Aug 13 '13 at 03:43

3 Answers3

5

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.

cuongle
  • 74,024
  • 28
  • 151
  • 206
1

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.

nhrobin
  • 873
  • 2
  • 7
  • 14
-1

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.

tymtam
  • 31,798
  • 8
  • 86
  • 126