Identifying Event Handlers

The upcoming .NET Whidbey release features two different mechanisms for identifying event handlers: interfaces and attributes. Which one is better? Richard puts both to the test.


July 01, 2004
URL:http://drdobbs.com/identifying-event-handlers/184407888

When you add an event to a class you actually add metadata that indicates that instances of the class can raise a named event of a specified type. The metadata also indicates the methods that are used to add a delegate to the event, so that the delegate will be called when the event is raised. There is no standard mechanism for a class to indicate that it can handle an event of a particular type. In this article, I will investigate this issue further.

I started thinking about this issue when I saw the new serialization attributes that will appear in version 2.0 of .NET (Whidbey). I won't go into great detail about this—I know that Juval Lowy is preparing an article on this subject (most likely for MSDN Magazine), so I'll leave the details to him. The current version of .NET (v1.1) serialization already allows you to provide a callback using the IDeserializationCallback interface, which has a single method, OnDeserialization. The idea is that once an object has been deserialized, but before it is returned from IFormatter.Deserialize, the object is given an opportunity to perform some more work. The class indicates that it wants to do this work by implementing the IDeserializationCallback interface, so the formatter specifically looks for this interface.

In Whidbey this idea is extended further, but instead of providing new interfaces, the designers have decided to use attributes. If you are an MSDN subscriber you can download the Visual Studio .NET Whidbey "community edition and take a look at these attributes. Basically, these attributes indicate the methods on the object that will be called at points before and after the object is deserialized. So you will have two mechanisms to indicate callback methods: using attributes, or using an interface. It does lack consistency and appears to be a bit of a mess.

Which mechanism is better? Well, I come from a COM background, so I am used to interfaces, so perhaps I am a bit biased. I decided to test the performance of both mechanisms and although the results agree with my prejudices the values still surprised me.

I defined an interface and an attribute:

interface ICallback
{
   void Call();
}
[AttributeUsage(AttributeTargets.Method)]
class CallbackAttribute : Attribute
{
}

Then I defined two classes, one that implemented the interface and another that marked its methods with the attribute. Neither of them did any work, they are just implemented as empty methods.

class InterfaceImpl : ICallback
{
   public void Call() { }
}
class AttributedMethods
{
   [Callback]
   public void Call() { }
} 

Next, I defined a class that had two methods to which an object is passed. The first method tests the object to see if it implements the interface, and if so, it creates a delegate and stores it; the other uses reflection to check all methods to find one that has the appropriate attribute, and again, if it has, a delegate is created and stored.

delegate void NoParameter();
 
class Caller
{
   event NoParameter delegates;
   public void PassInterfaceObject(object o)
   {
      ICallback cb = o as ICallback;
      if (cb != null)
      {
         delegates += new NoParameter(cb.Call);
      }
   }
   public void PassAttributedObject(object o)
   {
      MethodInfo[] methods = o.GetType().GetMethods();
      foreach(MethodInfo method in methods)
      {
         object[] attrs = method.GetCustomAttributes(typeof(CallbackAttribute), false);
         if (attrs.Length != 0)
         {
            delegates += (NoParameter)Delegate.CreateDelegate(
               typeof(NoParameter), o, method.Name);
         }
      }
   }
} 

The interface object method is straightforward. The reflection method is more complicated because it has to check every method for the required attribute, and once it has ascertained that the method has the attribute then the Delegate.CreateDelegate has to be used to create an appropriate delegate.

In my tests I have called each of these methods 1000 times and timed the total. As a comparison, I also measured the amount of time it takes each method to determine that a method does not have the attribute, or the object does not implement the interface. My results for 1000 calls are as follows:

PassInterfaceObject passed InterfaceImpl object: 0.00390s
PassAttributedObject passed AttributedMethods object: 0.07925s
PassInterfaceObject passed AttributedMethods object: 0.00012s
PassAttributedObject passed InterfaceImpl object: 0.03548s

The first point to make is that PassInterfaceObject is very quick to determine that an object does not implement an interface, whereas PassAttributedObject takes almost half its time determining that the object does not have an attributed method. Of course, the main point of this comparison is to compare the two mechanisms with objects that are acceptable, and this shows that the check for an interface and then adding the interface to the event takes almost half the time it takes to search for an attributed method and add that to the event. (Note that PassAttributedObject does continue to check for attributed methods even after it has found one, but when I changed the code to only check for one method it had little effect on the results.)

This analysis shows that the attributed mechanism is poor compared to the interface mechanism in terms of performance. Another argument is code readability, you could argue that it is more readable, and more immediately noticeable, to indicate event handlers with attributes rather than through interfaces. However, C# allows you to use the fully qualified interface name, which makes it more obvious that the method is an interface method. Compare these two amended classes:

class InterfaceImpl : ICallback
{
   public void ICallback.Call() { }
}
class AttributedMethods
{
   [Callback]
   public void Call() { }
} 

I think that it is just as readable to fully qualify the interface method as it is to use an attribute.

In my opinion the interface mechanism of identifying event handlers is better than the attribute mechanism.


Richard Grimes speaks at conferences and writes extensively on .NET, COM, and COM+. He is the author of Developing Applications with Visual Studio .NET (Addison-Wesley, 2002). If you have comments about this topic, Richard can be reached at [email protected].

Terms of Service | Privacy Statement | Copyright © 2024 UBM Tech, All rights reserved.