Spurred on by Nick Wienholt’s recent comments on the DOTNET list, I decided to finish off my investigation of the cost of dispatching virtual methods using an object reference vs. dispatching virtual methods using interface references, as illustrated by the following model system:
interface I1
{
void M1();
}
class C : I1
{
public virtual void M1() {}
}
There are two ways of calling the M1() virtual method in an instance of type C:
`C objRef = new C(); I1 itfRef = (I1)objRef;
objRef.M1(); itfRef.M1();`
As the code above shows, you can call M1() using an object reference, or you can call it using an interface reference. This causes the compiler to generate two completely different x86 instruction sequences:
// Call using an object reference
mov ecx, esi
mov eax, [ecx] ;get method table
call dword ptr [eax + zzz] ;call via method table
and
// Call using an interface reference
mov ecx, esi
mov eax, [ecx]
mov eax, [eax + zzz] ;get global itf table address
mov eax, [eax + zzz] ;get local itf table address
call dword ptr [eax + zzz] ;call via local itf table
The short answer is that on Pentium III-M CPU’s, there is no measurable performance difference between these two instruction sequences[1]. The full story can be found here.
If you read the fully story, you will find that you cannot accurately measure the relative dispatch cost using naive benchmarks. Hopefully this story will serve as an exemplar to others who would like to perform such investigations. As always, please send me feedback about this, or anything else that you read on this site.
[1] If you were to call a virtual method using one of these two techniques inside of a loop (the only case where the overhead imposed by the calling convention would ever be significant), you should see the cost of indirection completely hidden by the CPU. Note that these results would certainly be different if any of the mov instructions caused a cache miss, which would be unlikely after the first pass through the loop.