I've been a C++ developer for many years and switched to C# some time ago. Recently I started playing with dotPeek to recover some old code. I was surprised to see the code that came out of the decompiler looked so unoptimized. I started writing some code expecting the compiler to do expression folding and was astonished with the results. I wanted to share my observations and see what comments you may have as to why I'm seeing the results I'm seeing.
Compiler option Optimized on. .NET version 4.5.
First I'll share results I expected:
Console.Write(1 + 1 + 1); turned into Console.Write(3);
Console.Write ("a" + "b" + "c"); turned into Console.Write("abc");
Now here is where I was surprised:
string a = "aaaaa";
string b = "aaaaa";
Console.Write(b + a);
I expected the compiler to fold this expression to: output.Write("aaaaaaaaaa"); or at least output.Write(a+a); It did neither. It preserved the original. Surprised the compiler didn't notice the duplicate text and reference a single copy of it twice or fold the constants together. You may argue that I didn't add 'const'. (When I did that, the compiler did fold the expressions and removed the constants altogether). The variables are local and only used in this one place. The compiler should have noticed this and properly folded the expressions together without the 'const' property.
I did exactly the same experiment with int. The outcome was almost the same: when I used const int, it folded properly. When I removed the 'const' attribute
int c = 1, d = 1, e = 1;
Console.Write(c + d + e);
Resulted in:
int num1 = 1;
int num2 = 1;
int num3 = 1;
int num4 = num2;
Console.Write(num1 + num4 + num3);
This is totally bazar. I can't explain this one. The compiler wrote worse code. C++ compilers seem to do a lot better when it comes to expression folding.