views:

155

answers:

1

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?

+8  A: 
  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
Thanks Jon, you are so fast. I get it now.
Joan Venge
Attributes are just objects of reference types, so they're instantiated and stored in memory in exact same way any such other object is.
Pavel Minaev
...unless you're using something like http://www.postsharp.org/
TrueWill