Click here to Skip to main content
6,822,613 members and growing! (15,647 online)
Email Password   helpLost your password?
Languages » C# » General     Advanced

A General Fast Method Invoker

By Luyan

Method reflecting invoke is nice, but very frequently it can be too slow. This article describes an alternative method for dynamic method invoke.
C#, Windows, .NET, Visual-Studio, Dev
Posted:27 Jun 2006
Updated:4 Jul 2006
Views:81,543
Bookmarked:138 times
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
67 votes for this article.
Popularity: 8.84 Rating: 4.84 out of 5
2 votes, 3.0%
1

2
1 vote, 1.5%
3
4 votes, 6.0%
4
60 votes, 89.6%
5

Sample Image - FastMethodInvoker.gif

Introduction

Sometimes, I run across the need to dynamically invoke the method of an object, where the actual method might not be known until run-time. Usually, Reflecting is nice, but frequently doing it can be too slow. This article describes an alternative method for dynamic method invocation.

Background

When I read the article Fast Dynamic Property Accessors, I was thinking about my project, it has a lots of reflecting methods in circle. But it's methods not properties. But the DynamicMethod reminded me, maybe I could use Emit to generate a DynamicMethod to bind a special method before it can be invoked. I hope it will improve performance.

Using the Code

First, I reflected out the method which will be invoked:

MethodInfo methodInfo = typeof(Person).GetMethod("Say");

Then, I get the MethodInvoker to invoke:

FastInvokeHandler fastInvoker = GetMethodInvoker(methodInfo);
fastInvoker(new Person(), new object[]{"hello"});

Instead of using reflection method, invoke in the past:

methodInfo.Invoke(new Person(), new object[]{"hello"});

Implementation

First, I need to define a delegate to adapt the dynamic method:

public delegate object FastInvokeHandler(object target, 
                                   object[] paramters);

It looks the same as the class MethodInfo's Invoke method. Yes, that means I can write the same code to use it like in the past.

This code generates the DynamicMethod:

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++)
    {
        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]);
    }
    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]);
    }
    il.Emit(OpCodes.Ldarg_0);
    for (int i = 0; i < paramTypes.Length; i++)
    {
        il.Emit(OpCodes.Ldloc, locals[i]);
    }
    il.EmitCall(OpCodes.Call, methodInfo, null);
    if (methodInfo.ReturnType == typeof(void))
        il.Emit(OpCodes.Ldnull);
    else
        EmitBoxIfNeeded(il, methodInfo.ReturnType);
    il.Emit(OpCodes.Ret);
    FastInvokeHandler invoder = 
      (FastInvokeHandler)dynamicMethod.CreateDelegate(
      typeof(FastInvokeHandler));
    return invoder;
}

Conclusion

Well, I think this is a general way that can be used instead of most of the reflection methods to get about 50 times performance improvement. Any suggestions for improvements are welcome.

Extra advantage (reminded by MaxGuernsey): If an exception occurs in your code, FastInovker would throw the original one, but the Method.Invoke would throw a TargetInvocationException.

History

  • 2006-7-05: Updated to add static method support. Thanks Manuel Abadia.
  • 2006-6-30: Updated to add ref/out parameter support. Thanks Roger for his nice suggestion.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

Luyan


Member
I am currently working for a .NET framework names AgileFramework. It's introduction at here:
http://www.agilelabs.cn/agileframework

Now I'm living in China. I have been designing and developing .NET based software applications for 5+ years.
Location: China China

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 64 (Total in Forum: 64) (Refresh)FirstPrevNext
QuestionCan't work with 'struct' ? Pinmemberqmxle6:11 1 Oct '09  
GeneralExcellent! Accessibility fix possible. Pinmemberblack19813:49 22 Jul '09  
QuestionPartial Trust question PinmemberAndrey Belykh7:57 25 Apr '08  
Generalprivate member supported and easier way with better performance Pinmemberyzh_x20:38 1 Jul '07  
GeneralRe: private member supported and easier way with better performance PinmemberLinguar10:15 2 Jul '07  
GeneralRe: private member supported and easier way with better performance Pinmemberyzh_x17:44 2 Jul '07  
GeneralRe: private member supported and easier way with better performance PinmemberLinguar19:26 2 Jul '07  
GeneralWrapper PinmemberMick O'Neill14:46 7 Jun '07  
GeneralRe: Wrapper Pinmemberjohnnycrash9910:03 17 May '09  
GeneralComments and structure. PinmemberLinguar7:56 19 Mar '07  
GeneralRe: Comments and structure. PinmemberLuyan3:35 24 Mar '07  
GeneralA Wrapper class for your code Pinmemberbilly p10:35 6 Oct '06  
GeneralI think the result is not exact Pinmemberhappyhippyie1:10 3 Sep '06  
GeneralRe: I think the result is not exact Pinmemberueqt200720:42 1 Sep '07  
AnswerRe: I think the result is not exact Pinmemberxx9184:29 19 Jan '08  
QuestionMethodAccessException unhandled when using generic string types Pinmembercanerten3:20 9 Aug '06  
QuestionRe: MethodAccessException unhandled when using generic string types Pinmembercanerten3:47 9 Aug '06  
Questionany suggestion about 1.1 Pinmemberaibo1:46 8 Aug '06  
GeneralSpeed Difference ? PinmemberGreg Roberts23:18 25 Jul '06  
GeneralRe: Speed Difference ? PinmemberLinguar14:23 19 Mar '07  
GeneralRe: Speed Difference ? Pinmemberwildcatsoft21:48 14 Aug '08  
GeneralNice Pinmembermikeperetz18:36 20 Jul '06  
GeneralHow do you "invoke in the past"? Pinmemberzxcv12341234123412345:13 20 Jul '06  
QuestionNewbie to Reflection Pinmembershahp7:38 11 Jul '06  
AnswerRe: Newbie to Reflection PinmemberLuyan23:31 11 Jul '06  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads.

PermaLink | Privacy | Terms of Use
Last Updated: 4 Jul 2006
Editor: Smitha Vijayan
Copyright 2006 by Luyan
Everything else Copyright © CodeProject, 1999-2010
Web18 | Advertise on the Code Project