Reputation: 5553
I saw many articles about .NET Reflection performance, and I know that invoking the methods and retrieving the properties values using reflection is performance costly and it's about 2x-3x slower then direct calls.
But what about Type information and Attributes? I know that Types metadata is cached in .NET...so I think it's shouldn't be performance costly and it's something similar to searching in dictionaries or in lists (But I'm not sure)...
How slow is inspecting the Type information to check the Type of properties and getting Custom Attributes for properties types?
Does it bad practice and design to make many things to work based on attributes?
What I want to do, is to create some infrastructure for ASP.NET, that will inspect many controls and types for Custom Attributes in order to retrieve the information about required JavaScript files and client code that should be registered on page.
Upvotes: 2
Views: 1737
Reputation: 524
Building an architecture based on attribute is not a bad thing, but if you want to keep flexibility, you have to introduce an interface/implementation to provide these informations programatically independent to attributes and define a default implementation based on attributes.
Reading attributes is not slow but if you care about micro-optimization you can create your own cache like this :
static public class Metadata<T>
{
static public readonly Type Type = typeof(T); //cache type to avoid avcessing global metadata dictionary
static public class Attribute<TAttribute>
where TAttribute : Attribute
{
static public readonly TAttribute Value = Metadata<T>.Type.GetCustomAttributes(Metadata<TAttribute>.Type).SingleOrDefault() as TAttribute;
}
}
//usage
Metadata<MyType>.Attribute<MyAttributeType>.Value; //exception if more then once and null if not defined.
Upvotes: 5
Reputation: 12811
You'll get the best answer if you profile your use cases directly. A little reflection isn't bad, after all. A lot of reflection can be. Use the Stopwatch
class to time your alternatives.
Upvotes: 2