Advertisement
tomlev

Direct call vs. interface call

Aug 28th, 2011
2,588
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 0.75 KB | None | 0 0
  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. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement