views:

307

answers:

3

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);
+6  A: 

Yes, it does. You can verify this using by using ildasm or Reflector to inspect the code.

static void Main(string[] args) {
    string s = "A" + "B";
    Console.WriteLine(s);
}

is translated to

.method private hidebysig static void  Main(string[] args) cil managed {
    .entrypoint
    // Code size       17 (0x11)
    .maxstack  1
    .locals init ([0] string s)
    IL_0000:  nop
    IL_0001:  ldstr      "AB" // note that "A" + "B" is concatenated to "AB"
    IL_0006:  stloc.0
    IL_0007:  ldloc.0
    IL_0008:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000d:  nop
    IL_000e:  br.s       IL_0010
    IL_0010:  ret
} // end of method Program::Main

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:

static void Main(string[] args) {
    string s = "A" + "B";
    string t = "A" + "B";
    Console.WriteLine(Object.ReferenceEquals(s, t)); // prints true!
}

will print "True" on the console! This optimization is called string interning.

Jason
+4  A: 

According to Reflector:

Console.WriteLine("ABCDEF");
Console.WriteLine("ABCDEF");
Console.WriteLine("ABCDEF");

even in a Debug configuration.

Joey
A: 

You would be better to use Stringbuilder to perform the concatenation of strings as strings are immutable objects (the runtime has to create a new copy of the string) and hence suffer from a performance hit if you are concatenating strings frequently. Whereas StringBuilder is more efficient (not immutable) and is faster at concatenating strings.

tommieb75
Although true for general string manipulation, we're talking about string constants here which (as explained in more details by other answers) are combined at compile time, so are actually far more efficient than using a StringBuilder, which would have to do all it's work at runtime.
Simon P Stevens