daily pastebin goal
10%
SHARE
TWEET

Direct call vs. interface call

tomlev Aug 28th, 2011 1,108 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. void Main()
  2. {
  3.     Foo f = new Foo();
  4.     IFoo f2 = f;
  5.    
  6.     // JIT warm-up
  7.     f.Bar();
  8.     f2.Bar();
  9.    
  10.     int N = 10000000;
  11.     Stopwatch sw = new Stopwatch();
  12.    
  13.     sw.Start();
  14.     for (int i = 0; i < N; i++)
  15.     {
  16.         f.Bar();
  17.     }
  18.     sw.Stop();
  19.     Console.WriteLine ("Direct call: {0:F2}", sw.Elapsed.TotalMilliseconds);
  20.    
  21.     sw.Reset();
  22.     sw.Start();
  23.     for (int i = 0; i < N; i++)
  24.     {
  25.         f2.Bar();
  26.     }
  27.     sw.Stop();
  28.     Console.WriteLine ("Through interface: {0:F2}", sw.Elapsed.TotalMilliseconds);
  29.  
  30.  
  31.     // Results:
  32.     // Direct call:       23,28
  33.     // Through interface: 38,68
  34.  
  35. }
  36.  
  37. interface IFoo
  38. {
  39.     void Bar();
  40. }
  41.  
  42. class Foo : IFoo
  43. {
  44.     public virtual void Bar()
  45.     {
  46.     }
  47. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top