C#,结构 vs 类,更快? [英] C#, struct vs class, faster?
问题描述
可能的重复:
哪个最适合数据存储结构/类? >
考虑我有一个 Employee 对象的示例,该对象具有年龄、姓名、性别、职称、薪水等属性.我现在有一个列表,我想用一堆员工填充(每个 Employee 实例都是唯一的).
Consider the example where I have an Employee object with attributes like age, name, gender, title, salary. I now have a list i want to populate with a bunch of Employees (each Employee instance is unique).
就速度和内存占用而言,将员工创建为结构体还是类更可取?
In terms of just speed and memory footprint, is it more preferable to create the employee as a Struct or a Class?
欢迎在上述场景中提供有关结构与类的任何其他警告
Any additional caveats regarding Struct vs Class in the above scenario are welcome
推荐答案
结构仅用于应该具有类似值的行为的相对较小的结构.
Structs are to be used only for relatively small structures that should have value-like behaviour.
除非类型具备以下所有条件,否则不要定义结构特点:
- 它在逻辑上代表一个单一的值,类似于原始类型(整数、双精度等).
- 它的实例大小小于16 个字节.
- 它是不可变的.
- 不必经常装箱.
您的类型违反了前两条准则,可能也违反了第三条准则.所以你绝对应该在这里使用一个类.
Your type breaks the first two guidelines, and probably also the third. So you should definitely use a class here.
这篇关于C#,结构 vs 类,更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!