zoukankan      html  css  js  c++  java
  • 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

  • 相关阅读:
    C语言I作业12—学期总结
    C语言寒假大作战01
    C语言I作业12—学期总结
    C语言I博客作业11
    C语言I作业9
    C语言I博客作业08
    C语言I博客作业07
    C语言I博客作业05
    C语言I博客作业04
    C语言I博客作业03
  • 原文地址:https://www.cnblogs.com/lilei9110/p/5367947.html
Copyright © 2011-2022 走看看