DTO类与结构 [英] DTO classes vs. struct
问题描述
所以,这实际上是我当前的重点。
我正在努力重构我的个人项目,试图提高性能,优化内存使用率,使代码简单明了。我有不同的应用程序层(实际上是WAL服务的DAL,BLL,ServiceAgents)。我正在使用实体/模型/ DTO在这些层之间传递数据,这是无状态的(根本没有任何逻辑)。当前它们是这样的对象:
So, this is actually this question is my current keystone. I'm working on refactoring of my personal project, trying increase performance, optimize memory usage, make code easy and clear. I have a different application layers (actually, DAL, BLL, ServiceAgents which is WCF services). I'm using Entities/Models/DTOs to pass data between those layers, which is stateless (don't have any logic at all). Currently they're objects like this:
public class Person
{
public ComplexId Id { get; set; }
public string Name { get; set; }
// ...
}
我以前使用这种方法,就像最佳做法,是吗?这是存储传输数据的最佳方法吗?如果我这样更改 struct ,该怎么办:
I used to use such approach, it's like a "best practice", is it? Is this best way to store transferred data? What if I change it for struct like this:
public struct Person
{
public ComplexIdentifier ComplexId;
public string Name;
}
public struct ComplexIdentifier
{
public int LocalId;
public int GlobalId;
}
从性能/内存使用角度来看,这是更好的方法吗?还是可能有某些陷阱以这种方式起作用?
Is this would be better way from performance/memory usage perspective? Or maybe there is some kind of traps acting that way?
推荐答案
对于标准DTO实体,您将希望坚持使用此类
For standard DTO entities, you will want to stick with the class.
一个结构
具有比类更多的受限潜在用例范围。当 struct
类型过大时,也会存在效率问题(别忘了,它们是值类型,并且在传递时被复制),例如有关值类型的MSDN指南中概述的。当您开始通过属性公开 struct
类型时,更不用说大量陷阱了,或者在引用接口时将其意外装箱,或者使其可变。
A struct
has a much more limited range of potential use cases than classes. There are also efficiency issues when struct
types get too large (don't forget, they are value types and are copied when passed around), as outlined in the MSDN guidelines about value types. Not to mention plenty of gotchas when you start having struct
types exposed through properties, or accidentally box it when referencing interfaces, or make them mutable...
我不是说不在相关时使用 结构
,但我非常很少发现自己需要使用 struct
类型在我们的主桌面应用程序中-已分层并且具有DTO类型。
不能简单地通过
struct
vs。 class
。您将需要使用诸如 dotTrace 或 ANTS 以便找到热点并从那里去。性能问题并非微不足道,好的工具通常是答案的开始。
I'm not saying not to use struct
when it is relevant, but I very rarely find myself needing to use struct
types in our main desktop application - which is layered and features DTO types.
The performance issue cannot be answered as simply as
struct
vs. class
. You will need to employ a profiling tool such as dotTrace or ANTS in order to find the hotspots and go from there. Performance issues are not trivial and good tooling is usually the start of the answer.
这篇关于DTO类与结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!