I am a little bit disappointed in the CLR's optimizer. Suppose I have the following piece of code:
int i = 0;
for (int j = 0; j < 10; ++j)
++i;
Console.WriteLine("{0}", i);
It's clear that at the end of the loop the local variable 'i' should have the value 10. Modern C++ compilers would optimize this piece of code to a simple:
Console.WriteLine("{0}", 10);
To my surprise, the CLR JIT-compiler doesn't seem to be that smart. When I compile the piece of code above, then it iterates 10 times instead of assigning the value directly. Multithreading is no issue here, because all data access is on the stack and therefor thread-specific.
Can somebody point out how smart the CLR optimizer is? I don't see the use for the volatile
keyword, when the compiler doesn't optimize access to variables/fields.