سؤال

I have to do reflection and late binding so i don't know if there is a way to speed things up. Thought I would give it a shot.

This snippet takes about 15 seconds to complete which is way too slow, but seeing how I need to read the metadata.

private static object InvokeCall(Type HostObjectType, Object HostObject, CallType callType, string PropertyOrMethodName, object[] args)
{
    if (callType == CallType.Method)
    {
        return MyObjectType.InvokeMember(PropertyOrMethodName,System.Reflection.BindingFlags.InvokeMethod, null, myObject, args);
    }
}
هل كانت مفيدة؟

المحلول

I assume that 15s is when used in a loop; reflection isn't that slow.

You can speed up reflection (and invoke in particular) by obtaining the MethodInfo and using Delegate.CreateDelegate once. You then cache and re-use the resulting typed delegate (matching the expected call signature). Then use the typed delegate Invoke.

Note untyped delegate invoke is slow; it must be typed. Also; you can be sneaky and use a delegate with an extra (leading) parameter to invoke an instance method against a range of different objects, if you need the target object to change per-call.

For more complex scenarios, Expression or DynamicMethod are useful.

نصائح أخرى

Take a look to Fasterflect - A Fast and Simple Reflection API and Fast Invoker they are ready to use solutions and interesting to study.

If you want to go by your own way check articles: Dodge Common Performance Pitfalls to Craft Speedy Applications and Dynamically Compiled Lambdas vs. Pure Reflection

Try using an expression tree compiled lambda and cache the lambda. I've leveraged this extensively with great success.

http://kohari.org/2009/03/06/fast-late-bound-invocation-with-expression-trees/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top