Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property determinism

Is there any way in C# to mark a property as deterministic?

The reason I ask is that I often find myself declaring a local variable and reading a property into it, instead of accessing the property multiple times.

Is there any way that I can decorate the property as deterministic, such that the compiler could then optimize multiple accesses to that property? I am guessing in such a scenario that the class would need to be immutable, and decorated as such.

Is this something that even exists or am I clutching at straws?

like image 448
Matt Whitfield Avatar asked Sep 15 '10 08:09

Matt Whitfield


2 Answers

If the property is simple, like an implicit property:

public int X { get; set; }

or reading from a local variable:

public int X { get { return _x; } }

then the compiler will optimise the code so that there is no difference between accessing the property multiple times and putting the property in a variable and access that.

I verified this by comparing 100 million iterations of accessing a property ten times and copying the property to a variable and access that ten times, and there is no measuarable difference at all.

Generally properties should be leight-weight, so that you don't have to expect any heavy processing each time you access it. If the value for the property is costly to get, the class should cache the value internally so that reading the property only makes the costly operation the first time (lazy loading pattern).

If a property is costly to get each time, it shouldn't be a property at all, but a getter method.

like image 128
Guffa Avatar answered Sep 18 '22 17:09

Guffa


There is no mechanism in C# that allows you to introduce const property getters, i.e. getters that do not change the state of the object.

The Microsoft documentation simply recommends not to introduce any side-effects in your getters:

It is a bad programming style to change the state of the object by using the get accessor. For example, the following accessor produces the side effect of changing the state of the object every time that the number field is accessed.

private int number;
public int Number
{
    get
    {
        return number++;   // Don't do this
    }
}

As mentioned by Daren, another aspect to consider is multi-threading (unless your object is truly immutable). What if another thread changed the object state so that the getter should return a different value on the second call? There is no easy way for the compiler to make any guarantees, e.g. in the scenario below:

class List
{
    IList data;

    // called several times on thread A
    // property has no side-effects
    public int Count { get data.Length; }

    // called several times on thread B
    public void Add(object o)
    {
        data.Add(o);
    }
}
like image 21
Dirk Vollmar Avatar answered Sep 18 '22 17:09

Dirk Vollmar