I need to convert an open delegate (one in which the Target is not specified) into a closed one efficiently. I have profiled my code, and the cost of using CreateDelegate()
to produce a closed delegate for an instance method is a significant fraction (>60%) of the overall run time (as it takes place for each new instance of the type).
Some basic information about open and closed delegates is described on the MSDN site in the documentation for CreateDelegate
.
My current approach, is to find a way to cache the open delegate (so the cost of producing it is incurred just once) and invoke it using another method that supplies the implicit "this" parameter to the delegate.
A complicating factor is that I don't know the signature of the method that the delegate will represent at compile-time, other than through a generic parameter in the code. In addition, I want to avoid reflection (e.g. Invoke()
and DynamicInvoke()
) as they are no better in terms of performance.
static TDel CreateOpenDelegate<TDel>( MethodInfo mi )
{
// creates and returns an open delegate for a delegate of signature TDel
// that will invoke some method as described by MethodInfo {mi}
return (TDel)(object)Delegate.CreateDelegate( typeof(TDel), mi );
}
// simplification of some other code...
// Note that Action<T> is a sample usage, the actual delegate signature and
// invocation parameters vary, and are defined by the consumers of my code
private Action<T> myAction = CreateOpenDelegate<Action<U,T>>( someMethodInfo );
myAction( this, default(T) ); // can't do this since {this} is a hidden parameter...
I have already read Jon Skeet's article on Making Reflection Fly and Exploring Delegates, unfortunately, since I don't know the delegate signature in advance, I don't see a way to adapt the approach described there.
Any help would be appreciated.