开发者

Get Property Optimization when using loops

If I use loops in the get of a property, does this mean every time I call get on the property, it executes the loop? For eg, below, if I call CartViewModel.Total, does this mean it executes the loop inside SubTotal and Discount?

public class CartViewModel
{
    public decimal SubTotal { get { return CartViewItems.Sum(c => c.Price); } }
    public decimal Discount { get { return CartViewItems.Sum(c => Total-SubTotal); } }
    public decimal Total { get { return SubTotal-Discount; } }

    public List<CartViewItem> CartViewItems { get; set; }
}

public class CartViewItem
{
    public decimal Price { get; set; }
    publi开发者_开发问答c int ProductId { get; set; }
    public int Quantity { get; set; }
public float DiscountPercent {get; set;}
    public decimal SubTotal { get { return Price*Quantity; } }

    public decimal Total
    {
        get
        {
            return Convert.ToDecimal(((float)Price * (1 - (DiscountPercent / 100))
                       * Quantity));
        }
    }
}

Is there a way to optimize this?


Yes, every time you call the property, it will execute the loop.

Properties are really just syntactic sugar over method calls. Very nice syntactic sugar, but only sugar.

You might want to change CartViewModel to avoid exposing the list directly - instead, keep the list private, give some appropriate methods to mutate it (e.g. Add and Clear methods), probably make it implement IEnumerable<CartViewItem> itself, and keep track of the subtotal and discount as the list is mutated. That's assuming that CartViewItem is immutable, of course...

Alternatively (as John suggested), just make it more obvious that you're actually doing work, changing the properties to ComputeTotal(), ComputeDiscount() and ComputeSubTotal() methods.


I would recommend the "don't do that" approach.

Properties are meant for cases where the data being accessed are "almost like a field" in terms of performance and semantics. They are definitely not meant for cases where the property hides the fact that a more expensive operation is being performed.

Replace those properties with methods and see whether the calling code changes much. It will be clearer that you are doing something potentially expensive.

Depending on how often those are referenced, I might go further and inline the properties entirely. That might suggest some optimization in the callers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜