title: Speeding up Reflection Invoke C#/.NET
body: <p>There are plenty of posts on speeding up reflection invokes, examples here:</p>
  
  <p><a href="https://stackoverflow.com/questions/6430479/speeding-up-reflection-api-with-delegate-in-net-c">Speeding up Reflection API with delegate in .NET/C#</a></p>
  
  <p><a href="https://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates/" rel="nofollow noreferrer">https://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates/</a></p>
  
  <p>and here:</p>
  
  <p><a href="https://stackoverflow.com/questions/6430835/example-speeding-up-reflection-api-with-delegate-in-net-c">Example : Speeding up Reflection API with delegate in .NET/C#</a></p>
  
  <hr>
  
  <hr>
  
  <p>My question is about speeding up generic invokes. Is this possible at all?</p>
  
  <p>I've got an abstract class and a class which implements it...</p>
  
  <pre><code>public abstract class EncasulatedMessageHandler&lt;T&gt; where T : Message
  {
      public abstract void HandleMessage(T message);
  }
  
  public class Handler : EncasulatedMessageHandler&lt;MyMessageType&gt;
  {
      public int blat = 0;
      public override void HandleMessage(MyMessageType message) { blat++; }
  }
  </code></pre>
  
  <p>What I want to do is build up a list of these message handler classes and quickly invoke their HandleMessage()</p>
  
  <hr>
  
  <p>At the moment, I'm doing something that's approximately this:</p>
  
  <pre><code>object handler = Activator.CreateInstance(typeof(Handler)); // Ignore this, this is done up front.
  
  MethodInfo method = type.GetMethod("HandleMessage", BindingFlags.Instance | BindingFlags.Public);
  
  Action&lt;object&gt; hook = new Action&lt;object&gt;(delegate(object message)
  {
      method.Invoke(handler, new object[] { message });
  });
  
  // Then when I want to invoke it:
  
  hook(new MyMessageType());
  </code></pre>
  
  <hr>
  
  <p>That's not the whole thing, but it's the important stuff...</p>
  
  <p>The method.Invoke is very slow, I'd like to keep the generic parameters on the class, I realise I could lock this down to object and cast it in the HandleMessage method, but I'm trying to avoid doing this.</p>
  
  <p>Is there anything I can do to speed this up? It's currently orders of magnitude slower than direct calls.</p>
  
  <p>Any help would be appreciated.</p>