开发者

What about a mutable struct that's immutable from the standpoint of external code?

Update: It occurred to me after posting this question that the main downside of this idea would simply be that such a type would be easy to use improperly. That is, the type would have to be used in a very specific way to draw any benefits. What I originally had in mind was something that would be used like this (sticking with the SquareRootStruct example from the original question just for consistency):

class SomeClass
{
    SquareRootStruct _key;

    public SomeClass(int value)
    {
        _key = new SquareRootStruct(value);
    }

    public double SquareRoot
    {
        // External code would have to access THIS property for caching
        // to provide any benefit.
        get { return _key.SquareRoot; }
    }

    public SquareRootStruct GetCopyOfK开发者_StackOverflowey()
    {
        // If _key has cached its calculation, then its copy will carry
        // the cached results with it.
        return _key;
    }
}

// elsewhere in the code...
var myObject = new SomeClass();

// If I do THIS, only a COPY of myObject's struct is caching a calculation,
// which buys me nothing.
double x = myObject.GetCopyOfKey().SquareRoot;

// So I would need to do this in order to get the benefit (which is,
// admittedly, confusing)...
double y = myObject.SquareRoot;

So, considering how easy this would be to get wrong, I'm inclined to think that maybe Reed's right (in his comment) that this would make more sense as a class.


Suppose I have a struct that I want to have the following characteristics:

  1. Immutable from an external vantage point
  2. Fast to initialize
  3. Lazy calculation (and caching) of certain properties

Obviously the third characteristic implies mutability, which we all know is bad (assuming the mantra "Don't make mutable value types!" has been drilled into our heads sufficiently). But it seems to me that this would be acceptable as long as the mutable part is visible only internally to the type itself, and from outside code's perspective the value would always be the same.

Here's an example of what I'm talking about:

struct SquareRootStruct : IEquatable<SquareRootStruct>
{
    readonly int m_value;  // This will never change.

    double m_sqrt;         // This will be calculated on the first property
                           // access, and thereafter never change (so it will
                           // appear immutable to external code).

    bool m_sqrtCalculated; // This flag will never be visible
                           // to external code.

    public SquareRootStruct(int value) : this()
    {
        m_value = value;
    }

    public int Value
    {
        get { return m_value; }
    }

    public double SquareRoot
    {
        if (!m_sqrtCalculated)
        {
            m_sqrt = Math.Sqrt((double)m_value);
            m_sqrtCalculated = true;
        }

        return m_sqrt;
    }

    public bool Equals(SquareRootStruct other)
    {
        return m_value == other.m_value;
    }

    public override bool Equals(object obj)
    {
        return obj is SquareRootStruct && Equals((SquareRootStruct)obj);
    }

    public override int GetHashCode()
    {
        return m_value;
    }
}

Now, obviously this is a trivial example, as Math.Sqrt is almost certainly not costly enough to consider this approach worthwhile in this case. It's only an example for illustration purposes.

But my thinking is that this accomplishes my three objectives where the most obvious alternative approaches would not. Specifically:

  • I could perform the calculation in the type's constructor; but this would potentially fall short of the 2nd objective above (fast to initialize).
  • I could perform the calculation on every property access; but this would potentially fall short of the 3rd objective above (caching of calculated result for future accesses).

So yes, this idea would effectively lead to a value type that is internally mutable. However, as far as any external code could tell (as I see it), it would appear immutable, while bringing with it some performance benefits (again, I realize the above example would not be an appropriate use of this idea; the "performance benefits" I'm talking about would be contingent on the calculation actually being sufficiently costly to warrant caching).

Am I missing something, or is this in fact a worthwhile idea?


There's nothing wrong with having immutable data structures that internally use mutation (so long as the thread safety is well advertised). It's just that structs get copied all the time, so you can't do much with mutation. This isn't a problem in C/C++ because structs are usually passed by reference, whereas in C# it is rare to pass structs by reference. Since it's hard to reason about structs that are passed by value, mutable structs are discouraged in C#.


What you describe could probably work somewhat, but with an important caveat: the result of the slow calculation may or may not get stored when it is computed. For example, if the calculation is performed on the structs returned by an enumeration, the results will get stored in 'temporary' structs and will be discarded rather than propagated back into the ones stored in the data structure.


This looks similar to a Future. There was some mention of better support for Futures in C# 4.0 parallel extensions. (Like computing them on another core/thread in parallel to your normal work).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜