Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does .NET optimise properties with operations?

Tags:

c#

.net

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 am concern If I have 1,000,000 Interesting objects displayed in a custom GridView in a read only situation which shows SparePercentage via the property, the SparePercentage will be calculated over and over again or will there be optimised for example using a third _mSpareQtyPercentage which gets recalculated when Qty and SpareQty is set?

like image 396
Jake Avatar asked Dec 13 '22 06:12

Jake


1 Answers

I very much doubt that there's anything in the JIT which would perform that optimization for you - after all, that requires more work each time Qty and SpareQty are set, and more space per object. That's not a trade-off the JIT should be doing for you. You could do that yourself, of course - just don't expect either the C# or JIT compiler to do it for you.

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

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

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

like image 86
Jon Skeet Avatar answered Dec 14 '22 20:12

Jon Skeet