Two unrelated events caused me to spend some time this afternoon inside the debugger. This entry summarizes some of my observations regarding the cost of invoking a virtual method via an object reference vs. invoking the same virtual method via an interface reference.
The first event was Jim Miller’s excellent How does Hello, World really work? talk at the PDC. In this talk, one particular statement caught my attention: “Intel CPU’s are very good at optimizing away indirection. In fact, some of our best people back at Redmond cannot figure out what they are doing”. Unfortunately, Jim did not present any benchmark code or results to back up his claims, so I knew that I needed to check things out for myself … sometime.
The second event occurred this weekend when I spent some time reviewing the Methods chapter from Don’s forthcoming Essential .NET Volume 1. Don provides an excellent discussion about the mechanics of dispatching virtual methods and interface methods using only a single method table (as opposed to the multiple vtable mechanism used by C++). After reading his chapter, I finally had an excuse to take a look at how well Intel CPU’s can optimize away indirection: I can examine the cost of interface method dispatch (IMD) vs. virtual method dispatch (VMD).
The first thing to be aware is that there is a significant difference in the code that is generated by the JIT compiler. Let’s first consider the following simple program:
`interface I1 { void M1(); }
class C : I1 { public virtual void M1() {} }
static void Main(string[] args) { C c = new C(); c.M1();
I1 i1 = (I1)c;
i1.M1();`}
First, let’s look at the generated CIL for the Main() method:
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
// Code size 281 (0x119)
.maxstack 2
.locals init ([0] class C c,
[1] class I1 i1)
IL_0000: newobj instance void C::.ctor()
IL_0005: stloc.0
IL_0006: ldloc.0
IL_0007: callvirt instance void C::M1()
IL_000c: ldloc.0
IL_000d: stloc.1
IL_000e: ldloc.1
IL_000f: callvirt instance void I1::M1()
IL_0014: ret } // end of method Class1::Main
As you can see, there is no difference in the generated CIL code for calling the M1() and M2() methods, they both use the same instruction sequence. Below is the sequence for calling via the class reference:
IL_0006: ldloc.0
IL_0007: callvirt instance void C::M1()
Here is the instruction sequence for calling via the interface reference:
IL_000e: ldloc.1
IL_000f: callvirt instance void I1::M1()
However, things become dramatically different when we look at the generated x86 code. Here’s the instruction sequence for a call via an object reference:
// c.M1();
0440 mov ecx,edi ;esi contains objref
0442 mov eax,[ecx] ;get method table
0444 call dword ptr [eax+0x38] ;invoke via slot in MT
Here’s the instruction sequence for a call via an interface reference:
// i1.M1();
04af mov ecx,edi ;edi contains objref
04b1 mov eax,[ecx] ;get method table
04b3 mov eax,[eax+0xc] ;get global IT
04b6 mov eax,[eax+0x2c] ;get local IT
04b9 call dword ptr [eax] ;invoke via slot in IT
Note that there are two additional levels of indirection here.
Let’s put this code into a loop. Here’s some x86 code that calls the virtual method M1() 100,000,000 times via an object reference.
00be xor edi,edi ;i = 0
00c0 mov ecx,esi
00c2 mov eax,[ecx]
00c4 call dword ptr [eax+0x38]
00c7 inc edi
00c8 cmp edi,0x5f5e100 ;i < 100,000,000
00ce jl 00c0
Here’s some x86 code that calls the virtual method M1() 100,000,000 times via an interface reference:
00ec xor edi,edi ;i = 0
00ee mov ecx,esi
00f0 mov eax,[ecx]
00f2 mov eax,[eax+0xc]
00f5 mov eax,[eax+0x2c]
00f8 call dword ptr [eax]
00fa inc edi
00fb cmp edi,0x5f5e100 ;100,000,000
0101 jl 00ee
Both of the call instructions in the code fragments above target the same method:
01e0 ret
I believe that you would expect that the IMD code should take significantly longer to execute due to its two additional memory dereferences. So did I. But results are results.
Here’s the code for the test rig:
`const int MAX_COUNT = 100000000;
static long TimeVirtualMethodDispatch( C c ) { long vmdStart, vmdEnd; QueryPerformanceCounter( out vmdStart ); for( int i = 0; i < MAX_COUNT; i++ ) { c.M1(); } QueryPerformanceCounter( out vmdEnd ); return vmdEnd - vmdStart; }
static long TimeInterfaceMethodDispatch( I1 i1 ) { long imdStart, imdEnd; QueryPerformanceCounter( out imdStart ); for( int i = 0; i < MAX_COUNT; i++ ) { i1.M1(); } QueryPerformanceCounter( out imdEnd ); return imdEnd - imdStart; }
static void Main(string[] args) { C c = new C(); I1 i1 = (I1)c;
// Make sure that the methods are pre-compiled first TimeVirtualMethodDispatch( c ); TimeInterfaceMethodDispatch( i1 );
// Call above methods and output results to console }`
Click here to download the VS.NET project that contains the test rig code.
Here are the results:
Virtual method dispatch: 3.63 +/- 0.06 E+06 ticks Interface method dispatch: 4.12 +/- 0.07 E+06 ticks
Relative difference (IMD-VMD)/VMD * 100% = 13 +/- 1 %
If you’re interested in the raw results, click here for the Excel spreadsheet.
I wanted to compare the measured performance to the predicted performance based on instruction timings. However, when I looked through the Intel Instruction Set Reference Manual this afternoon, I couldn’t find any instruction timing information. I’m assuming that instruction timings in clocks are largely irrelevant due to internal caching, parallelization and out-of-order execution in modern CPU’s. If someone knows how to get the theoretical instruction timings for modern Intel CPU’s, please email me.
However, if we do a simple back-of-the envelope calculation and assume that each instruction in both sequences executes in a single clock, the VMD loop should complete in 7 clocks, and the IMD loop should complete in 9 clocks (the additional instruction is the ret instruction at the terminus of the call). In this case, we should see a 22% difference in performance, as opposed to the 12% that was observed. Clearly the CPU is doing some very interesting things, and the cost is not as high as we might expect.
NOTE: These results were obtained on my Thinkpad T-23 at 4:30pm on a cloudy afternoon in Toronto while sitting in the Starbucks at the Athletic Centre at the University of Toronto. Your mileage will vary. However, since this benchmark provides you with relative numbers, I doubt that there should be much variation. The one exception that I can think of is running the benchmark on CPU’s with different architectures. These numbers were from the Pentium III-M CPU in my laptop. I’ll run the same benchmark on some of my other machines to see what numbers they come up with.