惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

P
Proofpoint News Feed
博客园 - 聂微东
Application and Cybersecurity Blog
Application and Cybersecurity Blog
MyScale Blog
MyScale Blog
罗磊的独立博客
H
Help Net Security
L
LangChain Blog
T
Threat Research - Cisco Blogs
量子位
S
Securelist
Last Week in AI
Last Week in AI
L
Lohrmann on Cybersecurity
T
The Exploit Database - CXSecurity.com
P
Privacy International News Feed
The Hacker News
The Hacker News
Vercel News
Vercel News
D
Darknet – Hacking Tools, Hacker News & Cyber Security
C
Cybersecurity and Infrastructure Security Agency CISA
T
The Blog of Author Tim Ferriss
T
Threatpost
Security Latest
Security Latest
P
Palo Alto Networks Blog
Microsoft Security Blog
Microsoft Security Blog
NISL@THU
NISL@THU
F
Full Disclosure
WordPress大学
WordPress大学
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Stack Overflow Blog
Stack Overflow Blog
C
Check Point Blog
Hacker News - Newest:
Hacker News - Newest: "LLM"
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Heimdal Security Blog
J
Java Code Geeks
Recorded Future
Recorded Future
Hugging Face - Blog
Hugging Face - Blog
G
GRAHAM CLULEY
Know Your Adversary
Know Your Adversary
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
阮一峰的网络日志
阮一峰的网络日志
U
Unit 42
B
Blog RSS Feed
月光博客
月光博客
C
Cisco Blogs
V
Visual Studio Blog
D
DataBreaches.Net
H
Hacker News: Front Page
博客园 - 叶小钗
N
News and Events Feed by Topic
爱范儿
爱范儿
A
Arctic Wolf

博客园 - fanrsh

Javascript's Event 的一点总结 [转]SQL Server2005 SQLCLR代码安全之权限(3) [转]SQL Server2005 SQLCLR代码安全之权限(2) [转]SQL Server2005 SQLCLR代码安全之权限(1) Remoting事件序列一:客户端触发服务器端事件 jquery入门1:简单收缩菜单 - fanrsh - 博客园 jQuery工作原理解析以及源代码示例 ASP.NET 页面生存周期概览 Visual Studio 2005的版本情况和新特征详细介绍 Creating and writing ASP.NET 2.0 custom Configuration Sections 给大家一个CSS编辑工具,结合JQUERY用的很爽啊 flv视频是如何转的? codesmith学习资源 asp.net 事件验证 CSS循序渐进系列 [更新中]Lucene.net,中文分词技术 ICTCLAS研究 .net sql连接字符串详解 socket专家好文收藏 jQuery学习资源
推荐一个快速反射调用的类
fanrsh · 2007-08-28 · via 博客园 - fanrsh

使用传统的.net反射机制,调用类的方法时,在调用频率大的情况下,会感觉速度很慢。最近浏览卢彦的博客时,找到一个他改进后的反射调用类。试用以后感觉效率明显提高,特推荐给大家。作者重新实现了,反射调用方法,但是调用接口和.net原有方法一致。而且调用时抛出的异常为所调用类的实际异常,不像传统方式返回为包装异常。
文章来源:
http://www.codeproject.com/csharp/FastMethodInvoker.asp

快速反射调用类

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;

namespace FastMethodInvoker
{
    
class FastInvoke
    
{
        
public delegate object FastInvokeHandler(object target, object[] paramters);

        
static object InvokeMethod(FastInvokeHandler invoke, object target, params object[] paramters)
        
{
            
return invoke(null, paramters);
        }


        
public static FastInvokeHandler GetMethodInvoker(MethodInfo methodInfo)
        
{
            DynamicMethod dynamicMethod 
= new DynamicMethod(string.Empty, typeof(object), new Type[] typeof(object), typeof(object[]) }, methodInfo.DeclaringType.Module);
            ILGenerator il 
= dynamicMethod.GetILGenerator();
            ParameterInfo[] ps 
= methodInfo.GetParameters();
            Type[] paramTypes 
= new Type[ps.Length];
            
for (int i = 0; i < paramTypes.Length; i++)
            
{
                
if (ps[i].ParameterType.IsByRef)
                    paramTypes[i] 
= ps[i].ParameterType.GetElementType();
                
else
                    paramTypes[i] 
= ps[i].ParameterType;
            }

            LocalBuilder[] locals 
= new LocalBuilder[paramTypes.Length];

            
for (int i = 0; i < paramTypes.Length; i++)
            
{
                locals[i] 
= il.DeclareLocal(paramTypes[i], true);
            }

            
for (int i = 0; i < paramTypes.Length; i++)
            
{
                il.Emit(OpCodes.Ldarg_1);
                EmitFastInt(il, i);
                il.Emit(OpCodes.Ldelem_Ref);
                EmitCastToReference(il, paramTypes[i]);
                il.Emit(OpCodes.Stloc, locals[i]);
            }

            
if (!methodInfo.IsStatic)
            
{
                il.Emit(OpCodes.Ldarg_0);
            }

            
for (int i = 0; i < paramTypes.Length; i++)
            
{
                
if (ps[i].ParameterType.IsByRef)
                    il.Emit(OpCodes.Ldloca_S, locals[i]);
                
else
                    il.Emit(OpCodes.Ldloc, locals[i]);
            }

            
if (methodInfo.IsStatic)
                il.EmitCall(OpCodes.Call, methodInfo, 
null);
            
else
                il.EmitCall(OpCodes.Callvirt, methodInfo, 
null);
            
if (methodInfo.ReturnType == typeof(void))
                il.Emit(OpCodes.Ldnull);
            
else
                EmitBoxIfNeeded(il, methodInfo.ReturnType);

            
for (int i = 0; i < paramTypes.Length; i++)
            
{
                
if (ps[i].ParameterType.IsByRef)
                
{
                    il.Emit(OpCodes.Ldarg_1);
                    EmitFastInt(il, i);
                    il.Emit(OpCodes.Ldloc, locals[i]);
                    
if (locals[i].LocalType.IsValueType)
                        il.Emit(OpCodes.Box, locals[i].LocalType);
                    il.Emit(OpCodes.Stelem_Ref);
                }

            }


            il.Emit(OpCodes.Ret);
            FastInvokeHandler invoder 
= (FastInvokeHandler)dynamicMethod.CreateDelegate(typeof(FastInvokeHandler));
            
return invoder;
        }


        
private static void EmitCastToReference(ILGenerator il, System.Type type)
        
{
            
if (type.IsValueType)
            
{
                il.Emit(OpCodes.Unbox_Any, type);
            }

            
else
            
{
                il.Emit(OpCodes.Castclass, type);
            }

        }


        
private static void EmitBoxIfNeeded(ILGenerator il, System.Type type)
        
{
            
if (type.IsValueType)
            
{
                il.Emit(OpCodes.Box, type);
            }

        }


        
private static void EmitFastInt(ILGenerator il, int value)
        
{
            
switch (value)
            
{
                
case -1:
                    il.Emit(OpCodes.Ldc_I4_M1);
                    
return;
                
case 0:
                    il.Emit(OpCodes.Ldc_I4_0);
                    
return;
                
case 1:
                    il.Emit(OpCodes.Ldc_I4_1);
                    
return;
                
case 2:
                    il.Emit(OpCodes.Ldc_I4_2);
                    
return;
                
case 3:
                    il.Emit(OpCodes.Ldc_I4_3);
                    
return;
                
case 4:
                    il.Emit(OpCodes.Ldc_I4_4);
                    
return;
                
case 5:
                    il.Emit(OpCodes.Ldc_I4_5);
                    
return;
                
case 6:
                    il.Emit(OpCodes.Ldc_I4_6);
                    
return;
                
case 7:
                    il.Emit(OpCodes.Ldc_I4_7);
                    
return;
                
case 8:
                    il.Emit(OpCodes.Ldc_I4_8);
                    
return;
            }


            
if (value > -129 && value < 128)
            
{
                il.Emit(OpCodes.Ldc_I4_S, (SByte)value);
            }

            
else
            
{
                il.Emit(OpCodes.Ldc_I4, value);
            }

        }

    }

}


效果测试程序

using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;

namespace FastMethodInvoker
{
    
class Program
    
{
        
static void Main(string[] args)
        
{

            Type t 
= typeof(Person);
            MethodInfo methodInfo 
= t.GetMethod("Say");
            Person person 
= new Person();
            
string word = "hello";
            Person p 
= null;
            
object[] param = new object[] { word, p, 3 };
            
int TestTimes = 100000//测试次数,可自行调节看效果

            
传统方式反射

            
快速反射

            
直接调用
            
            Console.ReadLine();
        }

    }


    
public class Person
    
{
        
public void Say(ref string word, out Person p, int avi)
        
{
            word 
= "ttt" + avi.ToString();
            p 
= new Person();

            
//throw new System.Exception("出错了哦");
        }

    }

}