As far as I've understood attributes are generated at compile time (otherwise it would not be possible to load attributes via relflection). Anyhow, are there certain cases where attributes might lead to performance issues at runtime?
-
1No. If you look at the dotnet framwork code - _attributes everywhere :)_ e.g.:https://referencesource.microsoft.com/#System/compmod/system/collections/generic/linkedlist.cs,df5a6c7b6b60da4f – Mafii Jun 22 '17 at 08:25
-
1Attributes can be slow only when you try to access them (the attributes). Looking at them causes them to be created. – xanatos Jun 22 '17 at 08:26
-
3It never happens by accident, retrieving attributes at runtime requires explicit code. An attribute is not always the correct solution, [read this](https://stackoverflow.com/a/3378482/17034). – Hans Passant Jun 22 '17 at 08:44
2 Answers
Anyhow, are there certain cases where attributes might lead to performance issues at runtime?
Only if your program is excessively looking for attributes in your code.
Attributes are only useful when something is looking for it. If you decorate your class with [MyAwsomeAttribute]
and nothing is looking for it, then there will be no performance difference.
The performance difference will depend on how many attributes you have; if it was discovered; and the time it takes to execute the offending attribute (assuming it has this ability, many attributes are purely metadata).
Good examples are WCF custom behaviour attributes with their detailed and potentially complex implementation methods.
(To test out MickyD's answer)
Even this code, with a really evil attribute still has no performance impact because the attribute is never contructed.
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new Foo().ToString());
Console.ReadLine();
}
}
[ThrowExceptionAttribute]
public class Foo
{
}
public class ThrowExceptionAttribute : Attribute
{
public ThrowExceptionAttribute()
{
throw new NotImplementedException();
}
}
Of course if you do reflect over the attribute you can get performance impacts. But then your question becomes, "Can running arbitrary code have performance implications?".

- 7,443
- 1
- 34
- 61