Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# - Are properties recalculated everytime they are accessed?

Tags:

c#

properties

Assuming the following simple code:

private const int A = 2;
private const int B = 3;


public int Result
    {
        get
        {
            return A * B;
        }
    }

I am using the Result property a lot of times.
Is the product A*B recalculated every time?

like image 461
Alexander Karatarakis Avatar asked Apr 18 '11 15:04

Alexander Karatarakis


3 Answers

If you don't store the value in a private field, then yes it's going to recalculate upon every access.

A way to cache the results would be to

private int? _result;
public int Result {
  get {
     if (!_result.HasValue) {
       _result = A*B;
     }
     return _result.Value;
  }
}

There are several caveats here.

First, if all of your operations are against constants then the compiler will automatically optimize those away for you. Which means that the multiplication operation won't actually be performed at run time. Which means you shouldn't worry about it.

Second, if the operation is limited to performing a simple arithmetic operation against two existing variables, then computing it each time would be faster than the "if" test above. Also, local storage with a private field in this case would increase your memory footprint for no useful reason.

Third, if the underlying variables had changed between calls to the property getter (i.e. A or B has a new value), then this would NOT recompute with those new values.

Which leaves us with one of the few reasons to actually use the above code: The operation takes a long time and the data it operates on isn't changing between calls to the property. The only other reason I can think of at this moment to use this is if the property is an object that has to be instantiated before calling.

like image 67
NotMe Avatar answered Oct 18 '22 06:10

NotMe


There's nothing magical about properties. They're just syntactic sugar over two methods, get_Xxx and set_Xxx. Knowing that, it's clear that every time a property is accessed, all code inside get part gets executed.

like image 32
Anton Gogolev Avatar answered Oct 18 '22 06:10

Anton Gogolev


Since the values are const, the compiler might optimize this situation.

But if they aren't const, it will be calculated each time.

like image 32
Daniel A. White Avatar answered Oct 18 '22 06:10

Daniel A. White