设为首页 加入收藏

TOP

C#中使用反射的性能分析
2014-11-23 22:51:33 】 浏览:324
Tags:使用 反射 性能 分析

  最近在研究一个可配置系统的框架,在代码中大量使用了反射的方法,虽然借鉴到其他的语言,如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倍左右。


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇自定义线程池-c#的简单实现 下一篇用VisualC#实现文件大批量处理

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目