Choosing between immutable objects and structs for value objects

后端 未结 11 1564
鱼传尺愫
鱼传尺愫 2020-12-13 15:07

How do you choose between implementing a value object (the canonical example being an address) as an immutable object or a struct?

Are there performance, semantic or

11条回答
  •  遥遥无期
    2020-12-13 15:36

    In today's world (I'm thinking C# 3.5) I do not see a need for structs (EDIT: Apart from in some niche scenarios).

    The pro-struct arguments appear to be mostly based around perceived performance benefits. I would like to see some benchmarks (that replicate a real-world scenario) that illustrate this.

    The notion of using a struct for "lightweight" data structures seems way too subjective for my liking. When does data cease to be lightweight? Also, when adding functionality to code that uses a struct, when would you decide to change that type to a class?

    Personally, I cannot recall the last time I used a struct in C#.

    Edit

    I suggest that the use of a struct in C# for performance reasons is a clear case of Premature Optimization*

    * unless the application has been performance profiled and the use of a class has been identified as a performance bottleneck

    Edit 2

    MSDN States:

    The struct type is suitable for representing lightweight objects such as Point, Rectangle, and Color. Although it is possible to represent a point as a class, a struct is more efficient in some scenarios. For example, if you declare an array of 1000 Point objects, you will allocate additional memory for referencing each object. In this case, the struct is less expensive.

    Unless you need reference type semantics, a class that is smaller than 16 bytes may be more efficiently handled by the system as a struct.

提交回复
热议问题