zoukankan      html  css  js  c++  java
  • 使用委托优化反射

    1. delegate

    // 委托
    public delegate int AddMethod(int a, int b);
    
    // 实现
    var obj = new TestObject();
    var objType = obj.GetType();
    var add = objType.GetMethod("Add");
    var d = (AddMethod)Delegate.CreateDelegate(typeof(AddMethod), obj, add);
    
    for (var i = 0; i < _TIMES; i++) d(a, b);

    2. func

    var d = (Func<TestObject, int, int, int>)Delegate.CreateDelegate(typeof(Func<TestObject, int, int, int>), add);

    3. reflection

     var obj = new TestObject();
     var add = obj.GetType().GetMethod("Add");
     
     for (var i = 0; i < _TIMES; i++) add.Invoke(obj, new object[] {a, b});

    4. Test

    private static double _Run(string description, Action<int, int> action, int a, int b)
    {
    if (action == null) throw new ArgumentNullException("action");
    
    // 启动计时器
    var stopwatch = Stopwatch.StartNew();
    
    // 运行要测量的代码
    action(a, b);
    
    // 终止计时
    stopwatch.Stop();
    
    // 输出结果
    Console.WriteLine("{0}: {1}", description, stopwatch.Elapsed.TotalMilliseconds.ToString(CultureInfo.InvariantCulture));
    
    // 返回执行时间
    return stopwatch.Elapsed.TotalMilliseconds;
    }
  • 相关阅读:
    第三章-套接字编程
    unix网络编程第四章----基于TCP套接字编程
    unix网络编程第一章demo
    unix网络编程第2章
    论epoll的实现
    Select函数实现
    函数式编程语言
    Git
    python库-urllib
    PIL处理图片信息
  • 原文地址:https://www.cnblogs.com/asingna/p/5386243.html
Copyright © 2011-2022 走看看