Does C# do any compile-time optimization for constant string concatenation? If so, how must my code by written to take advantage of this?
Example: How do these compare at run time?
Console.WriteLine("ABC" + "DEF");
const string s1 = "ABC";
Console.WriteLine(s1 + "DEF");
const string s1 = "ABC";
const string s2 = s1 + "DEF";
Console.WriteLine(s2);
According to Reflector:
even in a Debug configuration.
Yes, it does. You can verify this using by using
ildasm
or Reflector to inspect the code.is translated to
There is something even more interesting but related that happens. If you have a string literal in an assembly, the CLR will only create one object for all instances of that same literal in the assembly.
Thus:
will print "True" on the console! This optimization is called string interning.