Question

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?

Was it helpful?

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.

OTHER TIPS

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();
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top