使用属性在.NET中的性能开销 [英] Performance overhead of using attributes in .NET

查看:237
本文介绍了使用属性在.NET中的性能开销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

1 ..有致的属性使用任何性能开销?想想一类,如:

 公共类MyClass的
    {
       诠释计数{获取;集;}
    }
 

其中有10 attibutes(属性为类,其中的属性类本身的方式比MyClass的本身一样大:

 公共类FirstAttribute:属性
{
   INT A,B,C,D,E,F,G,H,I,J ... {获取;集;}
}
 

2 ..请问10这些属性是内存开销,每次 MyClass的被实例化? ( FirstAttribute MyClass的将与10的这些装饰的10倍大小,所以在进行实际对象本身所以比较小的装饰就可以了属性的总大小。)这是一个问题?

3 ..请问这种情况有什么不同的结构(结构体是值类型和属性是引用类型)?

4 ..哪里存储在存储器中相对于物体attibutes它们所连接?它们是如何连接在一起?

5 ..后立即初始化为 MyClass的初始化属性或当您使用反射来检索他们?

解决方案
  1. 有开销在空间上一点点,但不是很多 - 属性没有得到正常执行的方式

  2. 没有,属性的类型,而不是实例的行为,所以你不会占用的内存大量使用大量的大的属性。 (我不知道你是否得到每具体的的一种仿制药,或每股普通类型定义 - 我期望后者...)

  3. 因为答案为1号。

  4. 属性没有附加到的对象 - 它们附着类型。我不知道的细节的完全的在那里他们存储在内存中,但是这是一个实现细节反正。

  5. 在使用反射属性仅初始化。

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

这篇关于使用属性在.NET中的性能开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆