Performance overhead of using attributes in .NET

2020-02-25 08:26发布

问题:

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? (FirstAttribute 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:

  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.



回答2:

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...