Can I have a concise code snippet that would incur JIT inlining please?

怎甘沉沦 提交于 2020-01-06 08:51:21

问题


I'm trying to produce some "Hello World" size C# code snippet that would incur JIT inlining. So far I have this:

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

    static Assembly GetAssembly()
    {
        return System.Reflection.Assembly.GetCallingAssembly();
    }
}

which I compile as "Release"-"Any CPU" and "Run without debugging" from Visual Studio. It displays the name of my sample program assembly so clearly GetAssembly() is not inlined into Main(), otherwise it would display mscorlib assembly name.

How do I compose some C# code snippet that would incur JIT inlining?


回答1:


Sure, here's an example:

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();
        }
    }
}

Compile in a release-like mode:

csc /o+ /debug- Test.cs

Run:

c:\Users\Jon\Test>test

Unhandled Exception: System.Exception: Exception of type 'System.Exception' was
thrown.
   at Test.Throw()
   at Test.Main()

Note the stack trace - it looks as if Throw was called directly by Main, because the code for CallThrow was inlined.




回答2:


Your understanding of inlining seems incorrect: If GetAssembly was inlined, it would still show the name of your program.

Inlining means: "Use the body of the function at the place of the function call". Inlining GetAssembly would lead to code equivalent to this:

class Program
{
    static void Main(string[] args)
    {
        Console.WriteLine(System.Reflection.Assembly.GetCallingAssembly()
                                                    .FullName);
        Console.ReadLine();
    }
}


来源:https://stackoverflow.com/questions/12686850/can-i-have-a-concise-code-snippet-that-would-incur-jit-inlining-please

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!