Practical advantage of generics vs interfaces

前端 未结 8 1537
梦毁少年i
梦毁少年i 2020-11-29 02:35

What would be a practical advantage of using generics vs interfaces in this case:

void MyMethod(IFoo f) 
{
}

void MyMethod(T f) : where T : IFoo
{
         


        
8条回答
  •  伪装坚强ぢ
    2020-11-29 03:11

    referring to the benchmark reported above

    @Branko, calling a method through an interface is actually slower than >a "normal" virtual method call... Here's a simple benchmark: >pastebin.com/jx3W5zWb – Thomas Levesque Aug 29 '11 at 0:33

    running the code in Visual Studio 2015 the result are roughly equivalent between Direct call and Through interface:

    • Direct call: 90,51 millisec; 112,49 millisec; 81,22 millisec
    • Through interface: 92,85 millisec;90,14 millisec; 88,56 millisec

    the code used to benchmark (from http://pastebin.com/jx3W5zWb ) is:

    using System;
    using System.Diagnostics;
    
    namespace test
    
    {
        class MainApp
        {
            static void Main()
            {
                Foo f = new Foo();
                IFoo f2 = f;
    
                // JIT warm-up
                f.Bar();
                f2.Bar();
    
                int N = 10000000;
                Stopwatch sw = new Stopwatch();
    
                sw.Start();
                for (int i = 0; i < N; i++)
                {
                    f2.Bar();
                }
                sw.Stop();
                Console.WriteLine("Through interface: {0:F2}", sw.Elapsed.TotalMilliseconds);
    
                sw.Reset();
    
                sw.Start();
                for (int i = 0; i < N; i++)
                {
                    f.Bar();
                }
                sw.Stop();
                Console.WriteLine("Direct call: {0:F2}", sw.Elapsed.TotalMilliseconds);
    
                Console.Read();
    
            }
    
            interface IFoo
            {
                void Bar();
            }
    
            class Foo : IFoo
            {
                public virtual void Bar()
                {
                }
            }
        }
    }
    

提交回复
热议问题