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;
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 :)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With