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?
If the property is simple, like an implicit property:
or reading from a local variable:
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.