在前面的文章中看了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.Run<TestMethod>();}}public class TestMethod{private readonly MyClass _myClass;private readonly Func<MyClass, string> _delegate;private readonly MethodInfo _methodinfo;public TestMethod(){_myClass = new MyClass();_methodinfo = _myClass.GetType().GetMethod("MyMethod");_delegate = (Func<MyClass, string>)Delegate.CreateDelegate(typeof(Func<MyClass, 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 = (Func<MyClass, string>)Delegate.CreateDelegate(typeof(Func<MyClass, string>), methodinfo);return dele(myClass);}}
可以看到反射的性能还是相对低的,同样委托实例化的性能也比较低。