开发者

Performance overhead of using attributes in .NET

1.. Is there any performance overhead caused by the usage of attributes? Think for a class like:

    public class MyClass
    {
       int Count {get;set;}
    }

where it has 10 attibutes (attributes being classes, where the attribute classes themselves are way larger than MyClass itself like:

public class FirstAttribute : Attribute
{
   int A,B,C,D,E,F,G,H,I,J ... {get;set;}
}

2.. Would 10 of these attributes be a memory overhead everytime MyClass is instantiated? (FirstAt开发者_运维知识库tribute being 10 times the size of MyClass which will be decorated with 10 of these, so making the actual object itself so small compared to the total size of the attributes that are decorated on it.) Is this a concern?

3.. Would this scenario be any different for structs (Structs being value types and attributes being reference types)?

4.. Where are attibutes stored in memory in relation to the object that they are attached? How are they hooked together?

5.. Are attributes initialized as soon as MyClass is initialized or when you use reflection to retrieve them?


  1. There's a tiny bit of overhead in terms of space, but not a lot - attributes don't get in the way of normal execution.

  2. No, attributes act on types, not instances, so you won't take up a vast amount of memory by using lots of "big" attributes. (I don't know whether you get one per concrete type for generics, or one per generic type definition - I'd expect the latter...)

  3. No, because of the answer to 1.

  4. Attributes aren't attached to objects - they're attached to types. I don't know the details of exactly where they're stored in memory, but that's an implementation detail anyway.

  5. Attributes are only initialized when you use reflection.


Jon Skeet is absolute right and I only want to give one additional notion:

If you have a look at the base class of all attributes, System.Attribute, you'll notice, that most of its members are static. So they exist only once, no matter how many Attribute instances you have.

This is just another point to underline, that Attributes are not too costly...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜