加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 03:52:30 所属栏目:百科 来源:网络整理
导读:基于随机Internet注释,我一直认为C#编译器对IL进行简单的优化(删除always-true if-statement,简单内联等),然后JIT执行真正的,复杂的优化. 就像the documentation for the /optimize compiler flag这样一个例子 The /optimize option enables or disables opt
基于随机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刚刚给抖动优化器足够的时间来消除关键的内存存储.这不经常发生.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读