Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a benefit of using IsDefined over GetCustomAttributes

Consider the case where an assembly contains one or more types attributed with a custom attribute MyAttribute and you need to get a list of these types. Is there any benefit of using IsDefined vs. GetCustomAttributes aside from the more compact syntax? Does one expose/hide something that the other doesn't? Is one more efficient than the other?

Here is a code sample demonstrating each usage:

Assembly assembly = ...
var typesWithMyAttributeFromIsDefined = 
        from type in assembly.GetTypes()
        where type.IsDefined(typeof(MyAttribute), false)
        select type;

var typesWithMyAttributeFromGetCustomAttributes = 
        from type in assembly.GetTypes()
        let attributes = type.GetCustomAttributes(typeof(MyAttribute), false)
        where attributes != null && attributes.Length > 0
        select type;
like image 266
Jay Walker Avatar asked Feb 05 '13 23:02

Jay Walker


2 Answers

Done a quick test with the two methods and it seems IsDefined is a lot faster than GetCustomAttributes

200000 iterations

IsDefined average Ticks = 54
GetCustomAttributes average Ticks = 114

Hope this helps :)

like image 78
sa_ddam213 Avatar answered Oct 20 '22 13:10

sa_ddam213


As Saddam demonstrates, IsDefined is more efficient than GetCustomAttributes. That's to be expected.

As documented here, applying attribute MyAttribute to class MyClass is conceptually equivalent to creating a MyAttribute instance. However, the instantiation does not actually occur unless MyClass is queried for attributes as with GetCustomAttributes.

IsDefined, on the other hand, does not instantiate MyAttribute.

like image 20
HappyNomad Avatar answered Oct 20 '22 14:10

HappyNomad