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; } // ... }
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?
For standard DTO entities, you will want to stick with the class. A struct has a much more limited range of potential use cases than classes.
DTOs come in handy in systems with remote calls, as they help to reduce the number of them. DTOs also help when the domain model is composed of many different objects and the presentation model needs all their data at once, or they can even reduce roundtrip between client and server.
A DTOs Structure. Data Transfer Objects are public (static) classes with no methods, other than the compiler supplied default constructor, having only public fields limited to the easily serializable types: i.e. A DTO is equivalent to a struct in C.
For standard DTO entities, you will want to stick with the class.
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...
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With