反射到底有多慢

一直听别人说 反射慢,但是真正的到底有多慢,你知道吗?反正我不知道。

具体的,我们上一下图。通过100000次计算后两个的值。

image

为了验证反射。首先来一个类:

简单一点 如下

public   class People
{
    public string Name { get; set; }

    public int Age { get; set; }
    public bool Sex { get; set; }
    public string ID { get; set; }
    public String Country { get; set; }
}

再来一个 反射赋值的方法(这里假设都有一个 无参数的构造方法。)

class AssimblelyHelp
   {
       /// <summary>
       /// 反射将T2的值付给T1
       /// </summary>
       /// <typeparam name="T"></typeparam>
       /// <param name="t1"></param>
       /// <param name="t2"></param>
       /// <returns></returns>
       public static T GetValue<T>(T t1, T t2) where T : new()

       {
           Type type = typeof(T);
           //获取默认的类型
           T temp =  new T();
           PropertyInfo[] propertys = type.GetProperties();
           foreach (var property in propertys)
           {
               if (property != null && property.GetValue(temp) != property.GetValue(t2))
               {
                   if (property.GetValue(t2)!=null)
                   {
                   property.SetValue(t1, property.GetValue(t2));
                   }
               }
              
           }


           return t1;
       }
   }

然后就是写的一个小小的 测试程序

public partial class Form1 : Form
  {
      public Form1()
      {
          InitializeComponent();
      }

      private void button1_Click(object sender, EventArgs e)
      {
          People people2 = new People() {Country = "china",ID = "222",Name = "小美人",Sex = false};
          People people1= new People(){Age=20};

          DateTime time0= DateTime.Now;
          for (int i =0; i < 100000; i++)
          {
              //Type type = typeof(People);
            //  var [] propertys = people2.GetType().GetProperties();

 


              AssimblelyHelp.GetValue(people1, people2);
          }
          DateTime time1= DateTime.Now;
          label1.Text = (time1 - time0).ToString();
          DateTime time2 = DateTime.Now;
          for (int i = 0; i < 100000; i++)
          {
              SetValue(people1); ;
          }
          DateTime time3 = DateTime.Now;
          label2.Text = (time3 - time2).ToString();
      }

      private static People SetValue(People people11)
      {
         // People people11 = new People();
          people11.Age = 18;
          people11.Country = "china";
          people11.ID = "222";
          people11.Name = "小美人";
          people11.Sex = false;
          return people11;
      }
  }

 

结论:反射的结果大约是19.66666666666667倍的时间。这还不算部分没有出现的属性。因为反射一样要花时间的。

posted @ 2015-10-15 11:45  临时工~  阅读(562)  评论(0编辑  收藏  举报