【发布时间】:2017-08-29 15:50:44
【问题描述】:
我不知道为什么,但我看到了从标准 c# 编译器 (VS2015) 生成的 IL,它在发布模式下明显没有优化。
我测试的代码很简单:
static void Main(string[] args)
{
int count = 25 + 7/3;
count += 100;
Console.WriteLine("{0}", count);
}
调试模式下的IL输出为:
// [12 9 - 12 10]
IL_0000: nop
// [34 13 - 34 34]
IL_0001: ldc.i4.s 27 // 0x1b
IL_0003: stloc.0 // count
// [35 13 - 35 26]
IL_0004: ldloc.0 // count
IL_0005: ldc.i4.s 100 // 0x64
IL_0007: add
IL_0008: stloc.0 // count
// [36 13 - 36 45]
IL_0009: ldstr "{0}"
IL_000e: ldloc.0 // count
IL_000f: box [mscorlib]System.Int32
IL_0014: call void [mscorlib]System.Console::WriteLine(string, object)
IL_0019: nop
// [37 9 - 37 10]
IL_001a: ret
Release模式下的代码是:
IL_0000: ldc.i4.s 27 // 0x1b
IL_0002: stloc.0 // V_0
IL_0003: ldloc.0 // V_0
IL_0004: ldc.i4.s 100 // 0x64
IL_0006: add
IL_0007: stloc.0 // V_0
IL_0008: ldstr "{0}"
IL_000d: ldloc.0 // V_0
IL_000e: box [mscorlib]System.Int32
IL_0013: call void [mscorlib]System.Console::WriteLine(string, object)
IL_0018: ret
现在,为什么编译器不执行 sum (27 + 100) 并直接调用 WriteLine with 127 ?
我在 c++ 中尝试了相同的示例,它按预期工作。
有一些特殊的标志来执行这种优化吗?
更新: 我在 MONO 4.6.20 上尝试了相同的代码,发布模式下的结果如下
// method line 2
.method private static hidebysig
default void Main (string[] args) cil managed
{
// Method begins at RVA 0x2058
.entrypoint
// Code size 18 (0x12)
.maxstack 8
IL_0000: ldstr "{0}"
IL_0005: ldc.i4.s 0x7f
IL_0007: box [mscorlib]System.Int32
IL_000c: call void class [mscorlib]System.Console::WriteLine(string, ob ject)
IL_0011: ret
} // end of method Program::Main
【问题讨论】:
-
您确定允许在
release模式下进行优化吗? -
是的,我也禁用了额外的调试或跟踪
-
你看过JIT编译的代码吗?在 .NET 中,大多数真正的优化是由 JIT 执行的,而不是 C# 编译器。
-
不,我不知道如何获得最终的 x86 代码。
-
请注意@Kyle 的说明,您必须确保要查看反汇编的代码已经执行了至少一次,因此在附加调试器之前代码已经被 JIT 过。在附加调试器的同时对代码进行 JIT 处理将导致生成不同的汇编代码。
标签: c# compiler-optimization cil