views:

384

answers:

2

Hi.

I would like to know whether the usage of Attributes in .Net, specifically C#, is expensive, and why or why not?

I am asking about C# specifically, unless there is no difference between the different .Net languages (because the base class libraries are the same?).

All the newer .Net technologies make extensive use of attributes, such as Linq to SQL, ASP.Net MVC, WCF, Enterprise Library, etc, and I was wondering what effect this would have on performance. Alot of the classes get automatically decorated with certain Attributes, or these attributes are required for certain functionality/features.

Does the question of expense depend on implementation specific details? How are Attributes compiled to IL? Are they cached automatically, or is this up to the implementor?

+10  A: 

"The usage of attributes" is too vague. Fetching the attributes is a reflection operation effectively - you wouldn't want to regularly do it in a loop - but they're not expensive to include in the metadata, and the typical usage pattern (IMO) is to build some other representation (e.g. an in-memory schema) after reading the attributes once.

There may well be some caching involved, but I'd probably cache the other representation anyway. For example, if I were decorating enum values with descriptions, I'd generally fetch the attributes once to build a string to enum dictionary (or vice versa).

Jon Skeet
Do you think one can safely assume that the attributes (or some representation of them) that are part of the .Net BCL and other Microsoft Frameworks/addons, are cached?
Saajid Ismail
Again, that's a bit vague. If you can give a very specific example and how one might determine whether or not they're cached, that would be a more reasonable question to answer.
Jon Skeet
+1  A: 

It depends on how you use them... Some attributes are just for information purpose (ObsoleteAttribute for instance), so they don't have any impact on runtime performance. Other attributes are used by the compiler (like DllImportAttribute) or by post-compilers like PostSharp, so the cost is at compile time, not run-time. However, if you use reflection to inspect attributes at runtime, it can be expensive.

Thomas Levesque