How to get assembly code generated by the JIT for a C# method

 
 
  • Gérald Barré

When you execute a .NET method, the JIT compiles the method to native code. This native code is then executed by the CPU. In this post, I describe how you can inspect the generated assembly code.

#Using the DOTNET_JitDisasm environment variable

Starting with .NET 7, you don't need any complex tools to inspect the generated assembly code. You can use the new environment variable DOTNET_JitDisasm with the name of the method to inspect. The following example shows how to inspect a method:

  • Create a new console application:

    dotnet new console
  • Add the following code to the Program.cs file:

    Program.cs (C#)
    Foo.Bar(); // Be sure the method is called, otherwise it won't be compiled by the JIT
    
    class Foo
    {
        public static void Bar()
        {
            Console.WriteLine("Hello World!");
        }
    }
  • Execute the code using the following environment variables:

    PowerShell
    $env:DOTNET_JitDisasm="Bar"
    dotnet run --configuration Release

  • You can also disable tiered compilation using the DOTNET_TieredCompilation environment variable. This ensures the method is compiled using the highest optimization level:

    PowerShell
    $env:DOTNET_JitDisasm="Bar"
    $env:DOTNET_TieredCompilation="0"
    dotnet run --configuration Release
Program.cs (C#)
using System.Runtime.CompilerServices;

Foo.Bar();

class Foo
{
    // Prevent the JIT from inlining the method
    [MethodImpl(MethodImplOptions.NoInlining)]
    public static void Bar()
    {
        Console.WriteLine("Hello World!");
    }
}

#Using Disasmo

Disasmo is a Visual Studio extension that allows you to inspect the generated assembly code from Visual Studio. It's much more convenient than using the DOTNET_JitDisasm environment variable and allows you to quickly enable options such as full optimizations or tiered compilation. Also, the method doesn't need to be called anywhere in the code.

#Using Sharplab

Sharplab is a very useful website that allows you to inspect the generated assembly code of a C# method. It's very convenient when you don't have Visual Studio installed or when you want to share a snippet with someone else. However, you cannot configure the JIT options such as full optimizations or tiered compilation.

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?Buy Me A Coffee💖 Sponsor on GitHub