为什么通过接口通过反射调用方法要快得多

Hus*_*awi -2 c# reflection interface

为什么通过反射调用方法比创建一个接口然后通过反射调用它要慢得多.第一个版本显示了其他版本显示增强方式的繁琐方式?

 // first version
  class A
    {
        public void fn()
        { 
        }
    }
  void Main(String[]x)
  {
        Type type = typeof(A);
        object obj = Activator.CreateInstance(type);
        type.InvokeMember("fn", BindingFlags.Public, null, obj, null);
  }

  //second verison
   interface IA
    {
        void fn();
    }

    class A :IA
    {
        public void fn()
        {
        }
    }

 void Main(String []x)
 {
        Type type = typeof(A);
        IA obj =(IA) Activator.CreateInstance(type);
        obj.fn();
 }
Run Code Online (Sandbox Code Playgroud)

SLa*_*aks 6

基于反射的方法调用非常慢,因为您需要在运行时执行成员查找和参数绑定等操作.

相反,接口方法callvirt使用vtable 通过常规指令调用.