Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>I find it completely implausible that a delegate is substantially faster or slower than a virtual method. If anything the delegate should be negligibly faster. At a lower level, delegates are usually implemented something like (using C-style notation, but please forgive any minor syntax errors as this is just an illustration):</p> <pre><code>struct Delegate { void* contextPointer; // What class instance does this reference? void* functionPointer; // What method does this reference? } </code></pre> <p>Calling a delegate works something like:</p> <pre><code>struct Delegate myDelegate = somethingThatReturnsDelegate(); // Call the delegate in de-sugared C-style notation. ReturnType returnValue = (*((FunctionType) *myDelegate.functionPointer))(myDelegate.contextPointer); </code></pre> <p>A class, translated to C, would be something like:</p> <pre><code>struct SomeClass { void** vtable; // Array of pointers to functions. SomeType someMember; // Member variables. } </code></pre> <p>To call a vritual function, you would do the following:</p> <pre><code>struct SomeClass *myClass = someFunctionThatReturnsMyClassPointer(); // Call the virtual function residing in the second slot of the vtable. void* funcPtr = (myClass -&gt; vtbl)[1]; ReturnType returnValue = (*((FunctionType) funcPtr))(myClass); </code></pre> <p>They're basically the same, except that when using virtual functions you go through an extra layer of indirection to get the function pointer. However, this extra indirection layer is often free because modern CPU branch predictors will guess the address of the function pointer and speculatively execute its target in parallel with looking up the address of the function. I've found (albeit in D, not C#) that virtual function calls in a tight loop are not any slower than non-inlined direct calls, provided that for any given run of the loop they're always resolving to the same real function.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload