问题
The IL code (generated with https://dotnetfiddle.net) of this piece of code:
public class Program
{
public static void Main()
{
int i = 10;
if (i < 4)
Console.WriteLine("Hello World");
}
}
contains ldstr "Hello World".
Shouldn't the compiler know that Console.WriteLine never gets executed?
The IL code of this:
public class Program
{
public static void Main()
{
if (10 < 4)
Console.WriteLine("Hello World");
}
}
doesn't contain the ldstr command.
Now i'm confused.. is the .NET compiler really that stupid? The C#/IL code of both examples do exactly the same: nothing. But the IL code of the first example is larger than the other. Shouldn't a good compiler just call the constructor and do nothing..?
Edit:
Yes i already read this but i'm not talking about additional generated locals.
If i
would be a propertie or a public variable, it would possible to modify it from another thread. But i
only exists in Main()...
回答1:
Here's the x64 disassembly of your snippet:
00007FF7C6083E0E add byte ptr [rax],al
--- C:\Dev\Temp\Test\ConsoleApp\ConsoleApp\Program.cs --------------------------
int i = 10;
00007FF7C6083E10 ret
--- No source file -------------------------------------------------------------
Which means, the JIT performed dead code elimination (ret
= return, the Main
function simply exits immediately).
The compiler only performs some basic optimizations, but the bulk of it is left to the JIT, to optimize for the platform it runs on.
Though I agree the compiler certainly could perform this optimization in this case, as it's platform-independent.
回答2:
The compiler acts as expected in my opinion. Compilers generally evaluate only constants and constant expressions, because their values are known at compile time. The variable "i" in your example and the expression "i < 4" are evaluated at run time and that is why the compiler does not optimize the code in this case.
回答3:
I also think that this should not be the responsibility of the debugger. Although everything is obvious in your sample, every line shows cumulative affect while calculating values, which is a enormous workload, take it as calculating the total Chess moves available. (There are billions of more moves available in chess than the all stars in the universe.)
来源:https://stackoverflow.com/questions/36010581/how-optimized-is-the-c-sharp-compiler