Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>I haven't seen that effect - I've certainly never encountered it being a bottleneck.</p> <p>Here's a very rough-and-ready benchmark which shows (on my box anyway) delegates actually being <em>faster</em> than interfaces:</p> <pre><code>using System; using System.Diagnostics; interface IFoo { int Foo(int x); } class Program : IFoo { const int Iterations = 1000000000; public int Foo(int x) { return x * 3; } static void Main(string[] args) { int x = 3; IFoo ifoo = new Program(); Func&lt;int, int&gt; del = ifoo.Foo; // Make sure everything's JITted: ifoo.Foo(3); del(3); Stopwatch sw = Stopwatch.StartNew(); for (int i = 0; i &lt; Iterations; i++) { x = ifoo.Foo(x); } sw.Stop(); Console.WriteLine("Interface: {0}", sw.ElapsedMilliseconds); x = 3; sw = Stopwatch.StartNew(); for (int i = 0; i &lt; Iterations; i++) { x = del(x); } sw.Stop(); Console.WriteLine("Delegate: {0}", sw.ElapsedMilliseconds); } } </code></pre> <p>Results (.NET 3.5; .NET 4.0b2 is about the same):</p> <pre><code>Interface: 5068 Delegate: 4404 </code></pre> <p>Now I don't have particular faith that that means delegates are <em>really</em> faster than interfaces... but it makes me fairly convinced that they're not an order of magnitude slower. Additionally, this is doing almost nothing within the delegate/interface method. Obviously the invocation cost is going to make less and less difference as you do more and more work per call.</p> <p>One thing to be careful of is that you're not creating a new delegate several times where you'd only use a single interface instance. This <em>could</em> cause an issue as it would provoke garbage collection etc. If you're using an instance method as a delegate within a loop, you will find it more efficient to declare the delegate variable outside the loop, create a single delegate instance and reuse it. For example:</p> <pre><code>Func&lt;int, int&gt; del = myInstance.MyMethod; for (int i = 0; i &lt; 100000; i++) { MethodTakingFunc(del); } </code></pre> <p>is more efficient than:</p> <pre><code>for (int i = 0; i &lt; 100000; i++) { MethodTakingFunc(myInstance.MyMethod); } </code></pre> <p>Could this have been the problem you were seeing?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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