微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

C#语言编译器是否自行执行任何实际的优化?

基于随机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");

Decompiled output:

if (true)
{
    Console.WriteLine("yo");
}

输入:

static void Donothing() { }

static void Main(string[] args)
{
    Donothing();
    Console.WriteLine("Hello World!");
}

Decompiled output:

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!");
}

Decompiled output:

try
{
    throw new Exception();
}
catch (Exception)
{
    Console.WriteLine("Hello World!");
}

如您所见,C#语言编译器似乎完全没有优化.

这是真的?如果是这样,为什么文档声称/ optimize会使您的可执行文件更小?

解决方法

我可以想到的唯一的优化是C#编译器执行,你可以用反编译器实际看到的是添加一个空的静态构造函数.

他们通常很无趣,只是更紧凑的IL.你只能看到它们,当你看着IL,一个体面的反编译器不会显示它.未优化的代码具有递归体系编译器的代码生成器的典型工件,紧随着相同变量的加载后的冗余存储分支到下一个地址.优化器知道如何消除它们.标准示例是发出的nop以帮助调试,它们允许您在大括号上设置断点.由优化器删除

没有什么可以提供一个容易观察到的perf改进,虽然你可能会幸运的是,更紧凑的IL刚刚给抖动优化器足够的时间来消除关键的内存存储.这不经常发生.

原文地址:https://www.jb51.cc/csharp/93556.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐