Performance issues when using C# attributes?

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?


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();
    }
}

[ThrowExceptionException]
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?".

链接地址: http://www.djcxy.com/p/39822.html

上一篇: 与结合的方程式推理

下一篇: 使用C#属性时的性能问题?