I have been reading different answers on which string concatenation operation is better. I read somewhere that "+" internally calls string.Concat
method and string.Concat
is faster between both. When I look at the IL code, it doesn't seem to suggest above statements.
For
string s1 = "1" + "2";
IL Code
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 8 (0x8)
.maxstack 1
.locals init ([0] string s1)
IL_0000: nop
IL_0001: ldstr "12"
IL_0006: stloc.0
IL_0007: ret
} // end of method Program::Main
Also, I noticed from the IL code that "+" initializes only one string whereas string.Concat initializes two strings to concatenate. I also tried with multiple strings as well. In terms of using the memory, "+" seems to use just one string variable where as the other option uses more variables internally.
For,
string s1 = string.concat("1", "2");
IL Code
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 18 (0x12)
.maxstack 2
.locals init ([0] string s1)
IL_0000: nop
IL_0001: ldstr "1"
IL_0006: ldstr "2"
IL_000b: call string [mscorlib]System.String::Concat(string,
string)
IL_0010: stloc.0
IL_0011: ret
} // end of method Program::Main
So can we conclude from above IL code that "+" is faster than "string.Concat" as it uses lesser variable for performing the same operation?