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

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

问题描述

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

它有 10 个属性(属性是类,属性类本身比 MyClass 本身大得多,例如:

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.. 每次实例化 MyClass 时,这些属性中的 10 个是否会成为内存开销?(FirstAttributeMyClass 大小的 10 倍,它将用其中的 10 个进行装饰,因此与属性的总大小相比,使实际对象本身非常小装饰.)这是一个问题吗?

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.. 这种情况对于结构体(结构体是值类型,属性是引用类型)会有什么不同吗?

3.. Would this scenario be any different for structs (Structs being value types and attributes being reference types)?

4.. 与它们所附加的对象相关的属性存储在内存中的什么位置?他们是怎么联系在一起的?

4.. Where are attibutes stored in memory in relation to the object that they are attached? How are they hooked together?

5.. MyClass 初始化后或使用反射检索属性时是否会立即初始化属性?

5.. Are attributes initialized as soon as MyClass is initialized or when you use reflection to retrieve them?

推荐答案

  1. 在空间方面有一点点开销,但不是很多 - 属性不会妨碍正常执行.

  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.

不,属性作用于类型,而不是实例,因此使用大量大"属性不会占用大量内存.(我不知道你是每个 concrete 类型获得一个泛型,还是每个泛型类型定义一个 - 我希望是后者......)

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

不,因为 1 的答案.

No, because of the answer to 1.

属性不附加到对象 - 它们附加到类型.我不知道它们在内存中存储位置的确切细节,但无论如何这是一个实现细节.

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.

只有在使用反射时才会初始化属性.

Attributes are only initialized when you use reflection.

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

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