I create a posting map in C # and basically just play with different approaches. I am interested to know about the difference in performance that I am measuring, but it is not obvious why looking at IL.
Message Card:
delegate void MessageHandler(Message message); AddHandler(Type t, MessageHandler handler) { } delegate void GenericMessageHandler<T>(T message); AddHandler<T>(GenericMessageHandler<T> handler) where T: Message { AddHandler(typeof(T), e => { handler((T)e); }); } Dictionary<Type, MessageHandler> messageMap;
Then I have a message class hierarchy similar to EventArgs in WPF, for example:
public class Message {} public class VelocityUpdateMessage : Message
and observer classes with handler functions:
void HandleVelocityUpdate(VelocityUpdateMessage message) { ... }
I am measuring 2 ways to add and call handlers. I am wrapping a delegate call, so I can get a little conceptual type of security, and that is the difference in level.
Approach 1: Listener Calls
AddHandler(typeof(VelocityUpdateMessage), e => { HandleVelocityUpdate((VelocityUpdateMessage)e); });
Approach 2: Listener Calls
AddHandler<VelocityUpdateMessage>(HandleVelocityUpdate);
Both approaches create a MessageHandler delegate that makes the cast the same method call, but calling delegates built using approach # 2 is slower, although the generated IL looks the same. Is this extra redundant runtime when casting to a generic type? Is this a type restriction? I would expect JITted delegates to be the same once the generic type is resolved.
Thanks for any info.