查看方法何时使用 WinDbg/SOS 编译 JIT 表明静态方法在调用它们之前没有编译。
考虑以下类:
class SomeType
{
[MethodImpl(MethodImplOptions.NoInlining)]
public void InstanceMethod()
{
Console.WriteLine("instance");
}
[MethodImpl(MethodImplOptions.NoInlining)]
public static void TypeMethod()
{
Console.WriteLine("type");
}
}
我使用 NoInlining 选项来防止编译器在发布版本中内联这些方法。
如果我运行一个像下面这样的小应用程序并附加 WinDbg,我可以观察到方法何时被 JIT 编译。
var st = new SomeType();
Console.WriteLine("attach");
Console.ReadLine();
Console.WriteLine("calling methods");
st.InstanceMethod();
SomeType.TypeMethod();
Console.ReadLine();
在附加方法表时,SomeType
如下所示:
0:004> !dumpmt -md 0041387c
EEClass: 004114d4
Module: 00412e94
Name: ConsoleApplication2.SomeType
mdToken: 02000007
File: c:\temp\ConsoleApplication1\ConsoleApplication1\bin\Release\ConsoleApplication1.exe
BaseSize: 0xc
ComponentSize: 0x0
Slots in VTable: 7
Number of IFaces in IFaceMap: 0
--------------------------------------
MethodDesc Table
Entry MethodDe JIT Name
6d374960 6d076728 PreJIT System.Object.ToString()
6d368790 6d076730 PreJIT System.Object.Equals(System.Object)
6d368360 6d076750 PreJIT System.Object.GetHashCode()
6d3616f0 6d076764 PreJIT System.Object.Finalize()
0041c035 00413874 NONE ConsoleApplication2.SomeType..ctor()
0041c02d 0041385c NONE ConsoleApplication2.SomeType.InstanceMethod()
0041c031 00413868 NONE ConsoleApplication2.SomeType.TypeMethod()
在显式调用方法后,它看起来像这样:
0:007> !dumpmt -md 0041387c
EEClass: 004114d4
Module: 00412e94
Name: ConsoleApplication2.SomeType
mdToken: 02000007
File: c:\temp\ConsoleApplication1\ConsoleApplication1\bin\Release\ConsoleApplication1.exe
BaseSize: 0xc
ComponentSize: 0x0
Slots in VTable: 7
Number of IFaces in IFaceMap: 0
--------------------------------------
MethodDesc Table
Entry MethodDe JIT Name
6d374960 6d076728 PreJIT System.Object.ToString()
6d368790 6d076730 PreJIT System.Object.Equals(System.Object)
6d368360 6d076750 PreJIT System.Object.GetHashCode()
6d3616f0 6d076764 PreJIT System.Object.Finalize()
0041c035 00413874 NONE ConsoleApplication2.SomeType..ctor()
004700e0 0041385c JIT ConsoleApplication2.SomeType.InstanceMethod()
00470110 00413868 JIT ConsoleApplication2.SomeType.TypeMethod()
即,在实际调用方法之前,它们不会被 JIT 编译。
(作为记录,这是在 .NET 4.5 上完成的)