我可以有一个简洁的代码片段来引发 JIT 内联吗?
题
我正在尝试生成一些“Hello World”大小的 C# 代码片段,这会导致 JIT 内联。到目前为止我有这个:
class Program
{
static void Main(string[] args)
{
Console.WriteLine( GetAssembly().FullName );
Console.ReadLine();
}
static Assembly GetAssembly()
{
return System.Reflection.Assembly.GetCallingAssembly();
}
}
我从 Visual Studio 编译为“发布”-“任何 CPU”和“无需调试即可运行”。它清晰地显示了我的示例程序程序集的名称 GetAssembly()
没有内联到 Main()
, ,否则会显示 mscorlib
程序集名称。
如何编写一些会导致 JIT 内联的 C# 代码片段?
解决方案
当然,这是一个例子:
using System;
class Test
{
static void Main()
{
CallThrow();
}
static void CallThrow()
{
Throw();
}
static void Throw()
{
// Add a condition to try to disuade the JIT
// compiler from inlining *this* method. Could
// do this with attributes...
if (DateTime.Today.Year > 1000)
{
throw new Exception();
}
}
}
以类似发布的模式进行编译:
csc /o+ /debug- Test.cs
跑步:
c:\Users\Jon\Test>test
Unhandled Exception: System.Exception: Exception of type 'System.Exception' was
thrown.
at Test.Throw()
at Test.Main()
注意堆栈跟踪 - 看起来好像 Throw
直接被调用 Main
, ,因为代码为 CallThrow
被内联。
其他提示
您对内联的理解似乎不正确:如果 GetAssembly
被内联,它仍然会显示你的程序的名称。
内联的意思是:“在函数调用的地方使用函数体”。内联 GetAssembly
将导致与此等效的代码:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(System.Reflection.Assembly.GetCallingAssembly()
.FullName);
Console.ReadLine();
}
}
不隶属于 StackOverflow