• 用BenchmarkDotNet看Method


      在前面的文章中看了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);
            }
        }

      可以看到反射的性能还是相对低的,同样委托实例化的性能也比较低。

     

     

     

      想要更快更方便的了解相关知识,可以关注微信公众号 

     

     

     

     

  • 相关阅读:
    MongoDB入门
    查看端口通不通
    jQuery通过name获取值
    thinking in java
    xml配置文件解释
    Spring定时器时间设置规则
    修改序列(Sequence)的初始值(START WITH)
    Go语言实现简单的一个静态WEB服务器
    [转载]XML非法字符的处理
    IIS7解决文件上传大小问题
  • 原文地址:https://www.cnblogs.com/ljknlb/p/15872808.html
Copyright © 2020-2023  润新知