Skip to content

String.Concat() or operator ‘+’

There are lots of discussions about what is the best method for strings concatenation: StringBuilder, String.Format() or String.Concat(). I think it is enough information about this, but recently my colleague expressed the opinion that String.Concat() works faster than concatenation with operator ‘+’. Is this the true?

Let’s find out the implementation of class String in .NET. I use dotPeek for decompiling assemblies.

Concat (for two strings):

public static string Concat(string str0, string str1)
{
    if (string.IsNullOrEmpty(str0))
    {
        if (string.IsNullOrEmpty(str1))
            return string.Empty;
        else
            return str1;
    }
    else
    {
        if (string.IsNullOrEmpty(str1))
            return str0;
        int length = str0.Length;
        string dest = string.FastAllocateString(length + str1.Length);
        string.FillStringChecked(dest, 0, str0);
        string.FillStringChecked(dest, length, str1);
        return dest;
    }
}

Operator +:

… nothing. There are overloading only for operators ‘==’ and ‘!=’ in String class. So the question is, how ‘+’ really works?

Let’s create simple application and compile it, and then inspect IL with ildasm. Here is source code:

public static void Main()
{
    string s1 = "Hello ";
    string s2 = "World";
    string s = s1 + s2;
}

Corresponding IL:

IL_0000: ldstr “Hello ”
IL_0005: stloc.0
IL_0006: ldstr “World”
IL_000b: stloc.1
IL_000c: ldloc.0
IL_000d: ldloc.1
IL_000e: call string [mscorlib]System.String::Concat(string,
string)

As we can see, operator ‘+’ was translated to call String.Concat() method. This means that it’s completely no difference and you can use what you like.