为什么 C# 编译器不内联 MSIL 代码?
Why doesn't the C# compiler inline MSIL code?
我的问题是为什么 C# 编译器不允许内联 C# MSIL 函数。我知道 JIT 在某些情况下会内联实际的 X86 程序集,但我问的是实际的 MSIL "assembly" 代码。
为什么 C# 编译器不提供这些类型的优化?
是因为收益微乎其微吗?或者根本就没有实施过?
a similar question for the Java compiler's optimizations when translating to JVM bytecode 的回复似乎是适用的。从高级语言(C# 或 Java)到中间语言(CIL/MSIL 或 JVM 字节码)的编译器可能不想优化其发出的代码,因为:
- 无论如何,中间代码将在运行时进行即时编译 (JIT),因此在编译时这样做会给编译器增加不必要的复杂性。
- 过早的优化实际上可能会阻碍 JITter 通过删除或复杂化元数据和中间代码来优化代码的能力。 Given the JIT knows more - the target processor, the usage patterns of the code, and so on - 这些优化更有效。
Eric Lippert's blog post on the C# compiler's /optimize
flag 支持编译器更喜欢做较少优化的概念,将其留给 .NET JIT:
These are very straightforward optimizations; there’s no inlining of IL, no loop unrolling, no interprocedural analysis whatsoever. We let the jitter team worry about optimizing the heck out of the code when it is actually spit into machine code; that’s the place where you can get real wins.
我的问题是为什么 C# 编译器不允许内联 C# MSIL 函数。我知道 JIT 在某些情况下会内联实际的 X86 程序集,但我问的是实际的 MSIL "assembly" 代码。
为什么 C# 编译器不提供这些类型的优化?
是因为收益微乎其微吗?或者根本就没有实施过?
a similar question for the Java compiler's optimizations when translating to JVM bytecode 的回复似乎是适用的。从高级语言(C# 或 Java)到中间语言(CIL/MSIL 或 JVM 字节码)的编译器可能不想优化其发出的代码,因为:
- 无论如何,中间代码将在运行时进行即时编译 (JIT),因此在编译时这样做会给编译器增加不必要的复杂性。
- 过早的优化实际上可能会阻碍 JITter 通过删除或复杂化元数据和中间代码来优化代码的能力。 Given the JIT knows more - the target processor, the usage patterns of the code, and so on - 这些优化更有效。
Eric Lippert's blog post on the C# compiler's /optimize
flag 支持编译器更喜欢做较少优化的概念,将其留给 .NET JIT:
These are very straightforward optimizations; there’s no inlining of IL, no loop unrolling, no interprocedural analysis whatsoever. We let the jitter team worry about optimizing the heck out of the code when it is actually spit into machine code; that’s the place where you can get real wins.