开发者

C# Attributes and Metadata implication

I read tutorials from the web about C# Attributes and Metadata. It's very cool but I'm wondering its implication.

  1. Are (custom) attributes loaded when the assembly is loaded? or is it only when you use reflection to retrieve the metadata?

  2. It seems the attributes add to the total of code size because it gets开发者_JAVA百科 compiled in to the executable? Is this right?

  3. Is it possible to have compile time attributes? I.e. attributes will only be applied if DEBUG is defined?

I know one is to do like this:

#if DEBUG
[MyCustomAttribute]
#endif

But I wonder if there's better way?

  1. Is there any performance/memory caveat when using a lot of attributes? My target platform will be Xbox 360 (using C#/XNA).

Thanks!

-Stephanus


There are two parts to attributes, their code and their constructor argument and property data. The code is stored in the IL of the assembly, the data is stored in the assembly metadata. If an attribute isn't used, that only takes up some virtual memory space but doesn't require any machine resources.

Nothing happens until you use the GetCustomAttributes() method. Then the code for the attribute class gets just-in-time compiled, just like the regular code in your assembly. And the constructor and the property setters are called, using the attribute data in the metadata. You'll use up some RAM for both when the memory manager maps the IL, machine code and the metadata pages.


1) AFAIK attributes are lazy-instantiated, but they come with the assembly into memory.
2) Not anywhere near enough to worry about. Knuth, etc.
3) Yes.

Using attributes means using reflection, which ranks among some of the slowest things you can do in the framework. But then, is it too slow for your application? Without knowing what you're doing, let alone what you need to do within how many milliseconds, noone can give you a yes or no answer to this.

Best thing is to whip up a prototype and see what its like IRL. Again, Knuth, etc.


  1. Attributes are loaded when the assembly is loaded. They are part of the type information, so are loaded with the types automatically.
  2. There is a (very small) cost in terms of assembly size with attributes. However, this is very minor, and not something of which I'd be concerned.
  3. You can do this, but only in the manner which you show.
  4. There is no performance impact of having attributes. They are ignored at runtime unless reflection is used to explicitly query for the attributes.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜