How does .NET optimize properties with operations?

For discussion, I have this class with properties

public class Intresting { decimal _mQty, _mSpareQty; public Qty { get { return _mQty; } set { _mQty = value; } } public SpareQty { get { return _mSpareQty; } set { _mSpareQty= value; } } public SparePercentage { get { return _mQty == 0 ? 0 : _mSpareQty / _mQty; } set { _SpareQty = Qty * value; } } } 

I'm concerned If I have 1,000,000 interesting objects displayed in a custom read-only GridView that shows SparePercentage through a property, SparePercentage will be calculated over and over again or will be optimized, for example using the third _mSpareQtyPercentage, which is recounted when Qty and SpareQty installed?

+4
source share
4 answers

I highly doubt that there is something in the JIT that will perform this optimization that requires more work each time Qty and SpareQty , and more space on the object. This is not a compromise that JIT should do for you. You can do it yourself, of course - just don't expect the C # or JIT compiler to do this for you.

I would expect the JIT compiler to include your trivial properties - which can be written as automatically implemented properties with C # 3:

 public decimal Quantity { get; set; } public decimal SpareQuantity { get; set; } 

(Pay attention to the changes to make the names more readable at the same time, by the way.)

+7
source

JIT will not do anything, in particular, to optimize this property, and therefore it will be reviewed in its entirety every time it requests. However, I doubt it will ever appear as a source of performance problems in your application. Of course, I would not go through troulbe to cache the result myself until the profile noticed that this is a problem in my application.

Note. It is also strange to have a property that has get, which is a computation and has a set at all. When there is calculation in the getter, I usually prefer to completely avoid the setter and instead force the caller to change the base values ​​that are the calculation parameter

+4
source

No, it will perform calculations every time it is called. If you want to avoid this, you will have to implement your own caching.

.NET does not "optimize" properties more than it optimizes any other functions.

+1
source

This is one of the reasons why it is not recommended to put more than the recipient in the support field. If an operation is performed, it must be performed in the method. There is nothing in the compiler that can make an assumption about how the code should be executed.

The pattern will execute the formula each time getter is called. OT, but in a streaming environment, I would expect that the only way to get the value would be a method call.

+1
source

Source: https://habr.com/ru/post/1390356/


All Articles