我可以提供一个简洁的代码片段,它会引发JIT内联吗?

sha*_*oth 0 .net c# jit inlining

我正在尝试制作一些会导致JIT内联的"Hello World"大小的C#代码片段.到目前为止我有这个:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine( GetAssembly().FullName );
        Console.ReadLine();
    }

    static Assembly GetAssembly()
    {
        return System.Reflection.Assembly.GetCallingAssembly();
    }
}
Run Code Online (Sandbox Code Playgroud)

我从Visual Studio编译为"Release" - "Any CPU"和"Run without debugging".它显示我的示例程序程序集的名称,因此显然GetAssembly()没有内联Main(),否则它将显示mscorlib程序集名称.

如何编写一些会导致JIT内联的C#代码片段?

Jon*_*eet 6

当然,这是一个例子:

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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

以类似于发布的模式编译:

csc /o+ /debug- Test.cs
Run Code Online (Sandbox Code Playgroud)

跑:

c:\Users\Jon\Test>test

Unhandled Exception: System.Exception: Exception of type 'System.Exception' was
thrown.
   at Test.Throw()
   at Test.Main()
Run Code Online (Sandbox Code Playgroud)

注意堆栈跟踪 - 看起来好像Throw是直接调用的Main,因为代码CallThrow是内联的.