Nugget: String concatenation compiler optimisation

William Brander responded to my last nugget on compiler optimization with a tweet about another one:

image

So what does that look like? Let’s examine the code we type:

string interesting = "first";
interesting += " second";
interesting += " third" + " forth";
interesting = interesting + " fifth";
interesting = interesting + " sixth" + " seventh";
Console.WriteLine(interesting);

And this optimizes the concatenation to a single line and drops the variable. Interesting use of braces—well, the reversion from += to =—for fifth and sixth though.

Console.WriteLine(("first" + " second" + " third" + " forth") + " fifth" + " sixth" + " seventh");