C#中使用反射的性能分析

出处:Examlink.com 作者:刀断水 日期:2008年07月08日 05时25分

  最近在研究一个可配置系统的框架,在代码中大量使用了反射的方法,虽然借鉴到其他的语言,如Java中反射性能都比较差,但是想到C#既然是一种强类型的语言,对于AppDomain中的类的调用应该性能不会差很多。
  今天在mvp站点上看到有人说反射的性能很差,要避免使用,就写了一个简单的例子测试了一下
  测试类如下:
  namespace ReflectionTest.Test
  {
  public class CTester
  {
  public CTester()
  {
  a = 10;
  }

  public void test1()
  {
  a = (a - 0.0001) * 1.0001;
  }
  private double a;
  public double geta() { return a; }
  }
  }
  首先我们对于对象的构造进行测试
  测试代码如下
  private void test1()
  {
  label1.Text = "";
  label3.Text = "";
  DateTime now = DateTime.Now;

  for (int i = 0; i < 1000; i++)
  {
  for (int j = 0; j < 100; j++)
  {

  CTester aTest = new CTester();
  }
  }

  TimeSpan spand = DateTime.Now - now;
  label1.Text = "time past " + spand.ToString();
  }

  private void test2()
  {
  label2.Text = "";
  label4.Text = "";
  DateTime now = DateTime.Now;

  for (int i = 0; i < 1000; i++)
  {
  for (int j = 0; j < 100; j++)
  {
  Type theTest = Type.GetType("ReflectionTest.Test.CTester");
  object theobj = theTest.InvokeMember(null, BindingFlags.CreateInstance
  , null, null, null);
  }
  }

  TimeSpan spand = DateTime.Now - now;
  label2.Text = "time past " + spand.ToString();
  }
  测试结果直接调用的时间为16ms左右,而反射调用的则始终维持在5s 520ms左右,直接效率比较接近350倍。
  对于这个测试,很有趣的一点是:
  如果将test2中的Type theTest = Type.GetType("ReflectionTest.Test.CTester");
  移到循环之外,则相应的运行时间下降为1s 332 ms , 效率相差为20倍左右。

最后更新时间:2008-11-05 07:32:49
文章评论
共有 0 位网友发表了评论
用户名: 新注册) 密码: 匿名评论 [查看所有评论]

评论内容:(不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。

考试全流程