In my previous posts (Performance Issues When Comparing Strings in .NET and When string.ToLower() is Evil) string related operations were discussed.
In this post we'll examine performance issues when querying for type member's custom attributes.
Let us define two attributes and a class. Class will have its single method decorated with an attribute. Here's the code:
class FooAttribute : Attribute { } class BarAttribute : FooAttribute { } class Item { [Bar] public int Action() { return 0; } }Now the question is what is the fastest way to check Action method for Bar custom attribute. Custom attributes can be queried using instance of a type that implements ICustomAttributeProvider interface. In our case we shall use Assembly class and MethodInfo.
The code below queries custom attributes using Assembly class and then using MethodInfo instance. Query operation executes 10000 times and duration is measured using Stopwatch class. Code below also measures time required to check if attribute is applied.
int count = 10000; Type tBar = typeof(Item); MethodInfo mInfo = tBar.GetMethod("Action"); //warm up mInfo.IsDefined(typeof(FooAttribute), true); object[] attribs = null; Stopwatch sw = new Stopwatch(); sw.Start(); for (int i = 0; i < count; i++) { attribs = Attribute.GetCustomAttributes(mInfo, typeof(FooAttribute), true); } sw.Stop(); Console.WriteLine("Attribute(specific): {0}, Found: {1}", sw.ElapsedMilliseconds, attribs.Length); sw.Reset(); sw.Start(); for (int i = 0; i < count; i++) { attribs = mInfo.GetCustomAttributes(typeof(FooAttribute), true); } sw.Stop(); Console.WriteLine("MethodInfo: {0}, Found: {1}", sw.ElapsedMilliseconds, attribs.Length); sw.Reset(); sw.Start(); for (int i = 0; i < count; i++) { attribs = Attribute.GetCustomAttributes(typeof(FooAttribute), true); } sw.Stop(); Console.WriteLine("Attribute(general): {0}, Found: {1}", sw.ElapsedMilliseconds, attribs.Length); sw.Reset(); sw.Start(); for (int i = 0; i < count; i++) { Attribute.IsDefined(mInfo, typeof(FooAttribute), true); } sw.Stop(); Console.WriteLine("Attribute::IdDefined: {0}", sw.ElapsedMilliseconds); sw.Reset(); sw.Start(); for (int i = 0; i < count; i++) { mInfo.IsDefined(typeof(FooAttribute), true); } sw.Stop(); Console.WriteLine("MethodInfo::IdDefined: {0}", sw.ElapsedMilliseconds); sw.Reset();Code above produces the output:
Attribute(specific): 137, Found: 1 MethodInfo: 130, Found: 1 Attribute(general): 569, Found: 1 Attribute::IdDefined: 40 MethodInfo::IdDefined: 33Results indicate that the fastest method is querying custom attributes via MethodInfo class. To generalize the results above we can say that the fastest way to get custom attributes - is to use the closest reflection equivalent of type member. (e.g. Method - MethodInfo, Property - PropertyInfo etc)
Last two results show the time of IsDefined operation. Use this operation in cases when only a check is needed whether attribute is applied to a type member.