Performance overhead of using attributes in .NET(在 .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 个是否会成为内存开销?(FirstAttribute
是 MyClass
大小的 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?
推荐答案
在空间方面有一点点开销,但不是很多 - 属性不会妨碍正常执行.
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 中使用属性的性能开销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 .NET 中使用属性的性能开销
基础教程推荐
- c# Math.Sqrt 实现 2022-01-01
- 将 XML 转换为通用列表 2022-01-01
- 有没有办法忽略 2GB 文件上传的 maxRequestLength 限制? 2022-01-01
- 如何在 IDE 中获取 Xamarin Studio C# 输出? 2022-01-01
- 为什么Flurl.Http DownloadFileAsync/Http客户端GetAsync需要 2022-09-30
- rabbitmq 的 REST API 2022-01-01
- 如何激活MC67中的红灯 2022-01-01
- 将 Office 安装到 Windows 容器 (servercore:ltsc2019) 失败,错误代码为 17002 2022-01-01
- MS Visual Studio .NET 的替代品 2022-01-01
- SSE 浮点算术是否可重现? 2022-01-01