Question

What is the best practice when using string builders in .NET regarding multiple calls of the .Append method vs. a single call to .Append while concatenating its parameters?

sb.Append(name).Append("; ");

vs.

sb.Append(name + "; ");

Is there any performance penalty when using one over the other? The second variant might in some cases be more readable (and is shorter to write).

Will doing such simple string concatenation of short strings nullify the performance/memory gains of using a string builder?

Was it helpful?

Solution

So I did a test appending text using three approaches in a loop 100,000 times.

(1)

    text += "Hello" + i.ToString();

(2)

    sb0.Append("Hello" + i.ToString());

(3)

    sb1.Append("Hello");
    sb1.Append(i.ToString());

The results were (1) took 108,332ms, (2) took 18ms, and (3) took 19ms.

So it turns out that simple concatenation is ever so slightly faster than two successive calls to the string builder. I suspect that was to do with garbage collections and not the actual speed of building the string.

The bottom-line is that you can use string concatenation without any trouble so long as the strings are relatively small.

OTHER TIPS

The second approach is slower than the first one (although, arguably not by much, so if it helps readability, it doesn't hurt). As a rule of thumb: use string.Format or string.Concat if appropriate, use StringBuilder whenever you are appending stuff in a loop.

I've done some performance testing using this approach:

var strings = Enumerable.Range(100000, 200000).Select(x => x.ToString()).ToArray();

var watch = new Stopwatch();
watch.Start();

for (var i = 0; i < 100000; ++i)
    // whatever method

var result = ...; // e.g. sb.ToString();
watch.Stop();

WriteResultToFile(result); // prevent optimizations
Console.WriteLine("Took: " + watch.ElapsedMilliseconds + "ms");

Results are as follows:

// Method 1: 39317ms
str += strings[i] + ", ";

// Method 2: 8ms
sb.Append(strings[i] + ", ");

// Method 3: 2ms
sb.Append(strings[i]);
sb.Append(", ");

// Method 4: 15ms
sb.Append(string.Format("{0}, ", strings[i]));

However, if you have a fixed number of strings to concatenate, please us string.Concat as it is able to pre-determine the resulting length and therefore is very performant.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top