title: Why is casting to a generic type slower than an explicit cast in C#?
body: <p>I'm building a message dispatch map in C# and mostly just playing around with some different approaches.  I am curious about a performance difference I am measuring, but it's not obvious why from looking at the IL.</p>
  
  <p>The message map:</p>
  
  <pre><code>delegate void MessageHandler(Message message);
  AddHandler(Type t, MessageHandler handler) 
  { 
      /* add 'handler' to messageMap invocation list */ 
  }
  
  delegate void GenericMessageHandler&lt;T&gt;(T message);
  AddHandler&lt;T&gt;(GenericMessageHandler&lt;T&gt; handler) where T: Message
  {
      AddHandler(typeof(T), e =&gt; { handler((T)e); });
  }
  
  Dictionary&lt;Type, MessageHandler&gt; messageMap;
  </code></pre>
  
  <p>I then have a class hierarchy of Messages, similar to EventArgs in WPF, for example:</p>
  
  <pre><code>public class Message {}
  public class VelocityUpdateMessage : Message
  </code></pre>
  
  <p>and observer classes with handler functions:</p>
  
  <pre><code>void HandleVelocityUpdate(VelocityUpdateMessage message) { ... }
  </code></pre>
  
  <p>I am measuring 2 ways of adding &amp; invoking handlers.  I am wrapping the delegate call so I can get a bit of conceptual type safety and therein lies the perf difference.</p>
  
  <p>Approach 1:  listener calls</p>
  
  <pre><code>AddHandler(typeof(VelocityUpdateMessage), 
             e =&gt; { HandleVelocityUpdate((VelocityUpdateMessage)e); });
  </code></pre>
  
  <p>Approach 2:  listener calls</p>
  
  <pre><code>AddHandler&lt;VelocityUpdateMessage&gt;(HandleVelocityUpdate);
  </code></pre>
  
  <p>Both approaches build a MessageHandler delegate that makes a cast and the same method call, but calling the delegates built using approach #2 is a wee bit slower even though the generated IL looks identical.  Is it extra runtime overhead in casting to a generic type?  Is it the type constraint?  I would expect the JITted delegates to be the same once the generic type is resolved.  </p>
  
  <p>Thanks for any info.</p>