网站开发专业怎么样,建站工具箱接线图,推广普通话喜迎十二大手抄报,互动平台官网在前面的文章中看了Property的几种不同访问方式《用BenchmarkDotNet看Property》#xff0c;性能调用上的差别明显#xff0c;那同样作为class里重要成员#xff0c;Method性能如何呢#xff1f;下面是被测试方法public class MyClass{public string MyMethod(){return Dat… 在前面的文章中看了Property的几种不同访问方式《用BenchmarkDotNet看Property》性能调用上的差别明显那同样作为class里重要成员Method性能如何呢下面是被测试方法public class MyClass{public string MyMethod(){return DateTime.Now.ToString();}}
具体调用方式实例化调用反射调用委托调用using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;namespace Demo01
{[MemoryDiagnoser]class MethodDemo : IDemo{public void Run(){BenchmarkRunner.RunTestMethod();}}public class TestMethod{private readonly MyClass _myClass;private readonly FuncMyClass, string _delegate;private readonly MethodInfo _methodinfo;public TestMethod(){_myClass new MyClass();_methodinfo _myClass.GetType().GetMethod(MyMethod);_delegate (FuncMyClass, string)Delegate.CreateDelegate(typeof(FuncMyClass, string), _methodinfo);}[Benchmark]public string MethodA(){return _myClass.MyMethod();}[Benchmark]public string MethodAExt(){var myClass new MyClass();return myClass.MyMethod();}[Benchmark]public string MethodB(){return _methodinfo.Invoke(_myClass, new object[0]).ToString();}[Benchmark]public string MethodBExt(){var myClass new MyClass();var methodinfo _myClass.GetType().GetMethod(MyMethod);return methodinfo.Invoke(myClass, new object[0]).ToString();}[Benchmark]public string MethodC(){return _delegate(_myClass);}[Benchmark]public string MethodCExt(){var myClass new MyClass();var methodinfo myClass.GetType().GetMethod(MyMethod);var dele (FuncMyClass, string)Delegate.CreateDelegate(typeof(FuncMyClass, string), methodinfo);return dele(myClass);}}
可以看到反射的性能还是相对低的同样委托实例化的性能也比较低。