基于随机Internet注释,我一直认为C#编译器对IL进行简单的优化(删除always-true if-statement,简单内联等),然后JIT执行真正的,复杂的优化.
就像the documentation for the /optimize
compiler flag这样一个例子
The /optimize option enables or disables optimizations performed by the compiler to make your output file smaller,faster,and more efficient.
这意味着语言编译器至少应用一些优化.
不过,与Try Roslyn一起玩,似乎并非如此.看起来C#编译器根本没有优化.
例子
输入:
bool y = true; if (y) Console.WriteLine("yo");
if (true) { Console.WriteLine("yo"); }
输入:
static void DoNothing() { } static void Main(string[] args) { DoNothing(); Console.WriteLine("Hello world!"); }
private static void DoNothing() { } private static void Main(string[] args) { NormalProgram.DoNothing(); Console.WriteLine("Hello world!"); }
输入:
try { throw new Exception(); } catch (Exception) { Console.WriteLine("Hello world!"); }
try { throw new Exception(); } catch (Exception) { Console.WriteLine("Hello world!"); }
如您所见,C#语言编译器似乎完全没有优化.
这是真的?如果是这样,为什么文档声称/ optimize会使您的可执行文件更小?
解决方法
@H_404_47@ 我可以想到的唯一的优化是C#编译器执行,你可以用反编译器实际看到的是添加一个空的静态构造函数.他们通常很无趣,只是更紧凑的IL.你只能看到它们,当你看着IL,一个体面的反编译器不会显示它.未优化的代码具有递归体系编译器的代码生成器的典型工件,紧随着相同变量的加载后的冗余存储分支到下一个地址.优化器知道如何消除它们.标准示例是发出的NOP以帮助调试,它们允许您在大括号上设置断点.由优化器删除
没有什么可以提供一个容易观察到的perf改进,虽然你可能会幸运的是,更紧凑的IL刚刚给抖动优化器足够的时间来消除关键的内存存储.这不经常发生.