Performance overhead of using attributes in .NET

前端 未结 2 752
野的像风
野的像风 2020-12-30 06:37

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

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


        
相关标签:
2条回答
  • 2020-12-30 07:06

    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 讨论(0)
  • 2020-12-30 07:15
    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.

    0 讨论(0)
提交回复
热议问题