gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 09:13:34 36 4
gpt4 key购买 nike

根据随机的 Internet 评论,我一直认为 C# 编译器对 IL (删除始终为真的 if 语句、简单的内联等) 进行了简单的优化,然后是 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,它们允许您在大括号上设置断点。被优化器删除。

虽然您可能很幸运,更紧凑的 IL 恰好为抖动优化器提供了足够的时间来消除关键内存存储,但没有什么可以提供易于可观察到的性能改进。这种情况并不经常发生。

关于c# - C# 语言编译器是否自行执行任何实际优化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35092069/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com