Choosing between immutable objects and structs for value objects

后端 未结 11 1543
鱼传尺愫
鱼传尺愫 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:53

    Factors: construction, memory requirements, boxing.

    Normally, the constructor restrictions for structs - no explicit parameterless constructors, no base construction - decides if a struct should be used at all. E.g. if the parameterless constructor should not initialize members to default values, use an immutable object.

    If you still have the choice between the two, decide on memory requirements. Small items should be stored in structs especially if you expect many instances.

    That benefit is lost when the instances get boxed (e.g. captured for an anonymous function or stored in a non-generic container) - you even start to pay extra for the boxing.


    What is "small", what is "many"?

    The overhead for an object is (IIRC) 8 bytes on a 32 bit system. Note that with a few hundred of instances, this may already decide whether or not an inner loop runs fully in cache, or invokes GC's. If you expect tens of thousands of instances, this may be the difference between run vs. crawl.

    From that POV, using structs is NOT a premature optimization.


    So, as rules of thumb:

    If most instances would get boxed, use immutable objects.
    Otherwise, for small objects, use an immutable object only if struct construction would lead to an awkward interface and you expect not more than thousands of instances.

提交回复
热议问题