码迷,mamicode.com
首页 > Windows程序 > 详细

C#成员函数直接调用和反射+委托的性能比较

时间:2016-04-08 14:42:19      阅读:241      评论:0      收藏:0      [点我收藏+]

标签:

using System;
using System.Reflection;
using System.Diagnostics;

namespace Refl
{
	class Test
	{
		public void Method()
		{
		}
	}

	class MainClass
	{
		const int loops = 100000000;
		Test m_Test = new Test();
		Action m_Action;

		public MainClass()
		{
			Type t = typeof(Test);
			MethodInfo m = t.GetMethod("Method");
			m_Action = (Action)Delegate.CreateDelegate(typeof(Action), m_Test, m);
		}

		public void Test1()
		{
			Stopwatch stopWatch = new Stopwatch();
			stopWatch.Start();
			for (int i = 0; i < loops; ++i)
			{
				m_Test.Method();
			}
			stopWatch.Stop();

			Console.WriteLine("Test1 - direct invoke: " + stopWatch.ElapsedMilliseconds);
		}

		public void Test2()
		{
			Stopwatch stopWatch = new Stopwatch();
			stopWatch.Start();
			for (int i = 0; i < loops; ++i)
			{
				m_Action();
			}
			stopWatch.Stop();

			Console.WriteLine("Test2 - delegate invoke: " + stopWatch.ElapsedMilliseconds);
		}

		public static void Main(string[] args)
		{
			MainClass main = new MainClass();
			main.Test1();
			main.Test2();

			Console.ReadKey();
		}
	}
}

Xamarin - Release结果

第一次:

Test1 - direct invoke: 633 ms

Test2 - delegate invoke: 527 ms

 

第二次

Test1 - direct invoke: 644 ms

Test2 - delegate invoke: 661 ms

 

第三次

Test1 - direct invoke: 621 ms

Test2 - delegate invoke: 646 ms

C#成员函数直接调用和反射+委托的性能比较

标签:

原文地址:http://www.cnblogs.com/lilei9110/p/5367947.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!