Search code examples
c#vb.netperformancestringbuilderstring.format

Is String.Format as efficient as StringBuilder


Suppose I have a stringbuilder in C# that does this:

StringBuilder sb = new StringBuilder();
string cat = "cat";
sb.Append("the ").Append(cat).(" in the hat");
string s = sb.ToString();

would that be as efficient or any more efficient as having:

string cat = "cat";
string s = String.Format("The {0} in the hat", cat);

If so, why?

EDIT

After some interesting answers, I realised I probably should have been a little clearer in what I was asking. I wasn't so much asking for which was quicker at concatenating a string, but which is quicker at injecting one string into another.

In both cases above I want to inject one or more strings into the middle of a predefined template string.

Sorry for the confusion


Solution

  • NOTE: This answer was written when .NET 2.0 was the current version. This may no longer apply to later versions.

    String.Format uses a StringBuilder internally:

    public static string Format(IFormatProvider provider, string format, params object[] args)
    {
        if ((format == null) || (args == null))
        {
            throw new ArgumentNullException((format == null) ? "format" : "args");
        }
    
        StringBuilder builder = new StringBuilder(format.Length + (args.Length * 8));
        builder.AppendFormat(provider, format, args);
        return builder.ToString();
    }
    

    The above code is a snippet from mscorlib, so the question becomes "is StringBuilder.Append() faster than StringBuilder.AppendFormat()"?

    Without benchmarking I'd probably say that the code sample above would run more quickly using .Append(). But it's a guess, try benchmarking and/or profiling the two to get a proper comparison.

    This chap, Jerry Dixon, did some benchmarking:

    http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm

    Updated:

    Sadly the link above has since died. However there's still a copy on the Way Back Machine:

    http://web.archive.org/web/20090417100252/http://jdixon.dotnetdevelopersjournal.com/string_concatenation_stringbuilder_and_stringformat.htm

    At the end of the day it depends whether your string formatting is going to be called repetitively, i.e. you're doing some serious text processing over 100's of megabytes of text, or whether it's being called when a user clicks a button now and again. Unless you're doing some huge batch processing job I'd stick with String.Format, it aids code readability. If you suspect a perf bottleneck then stick a profiler on your code and see where it really is.