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

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: 621
Test2 - delegate invoke: 646

Visual Studio - Release

Test1 - direct invoke: 240
Test2 - delegate invoke: 261

转载于:https://www.cnblogs.com/lilei9110/p/5367947.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值