Why is it okay that this struct is mutable? When are mutable structs acceptable?

前端 未结 5 1008
野趣味
野趣味 2020-12-29 02:35

Eric Lippert told me I should \"try to always make value types immutable\", so I figured I should try to always make value types immutable.

But, I just found this i

5条回答
  •  轮回少年
    2020-12-29 03:08

    Actually, if you search for all classes containing BitVector in the .NET framework, you'll find a bunch of these beasts :-)

    • System.Collections.Specialized.BitVector32 (the sole public one...)
    • System.Web.Util.SafeBitVector32 (thread safe)
    • System.Web.Util.SimpleBitVector32
    • System.Runtime.Caching.SafeBitVector32 (thread safe)
    • System.Configuration.SafeBitVector32 (thread safe)
    • System.Configuration.SimpleBitVector32

    And if you look here were resides the SSCLI (Microsoft Shared Source CLI, aka ROTOR) source of System.Configuration.SimpleBitVector32, you'll find this comment:

    //
    // This is a cut down copy of System.Collections.Specialized.BitVector32. The
    // reason this is here is because it is used rather intensively by Control and
    // WebControl. As a result, being able to inline this operations results in a
    // measurable performance gain, at the expense of some maintainability.
    //
    [Serializable()]
    internal struct SimpleBitVector32
    

    I believe this says it all. I think the System.Web.Util one is more elaborate but built on the same grounds.

提交回复
热议问题