Search code examples
c#.netjitinlining

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


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?


Solution

  • 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.