C#C
C#2y ago
Cryy

Performance question

Hey guys,

I have an web app and I tried to optimize the performance of one report. One stuff that seems unefficient to me is this one:

var searchedResults = query.Count();
if (index.HasValue && pageSize.HasValue)
{
    query = query.Skip(index.Value).Take(pageSize.Value);
}

var result = query.ToList();

var total = new SimsSiteInventoryReportData
{
    QuantityOnSite = query.Sum(q => q.QuantityOnSite),
    QuantityDispatchedToSite = query.Sum(q => q.QuantityDispatchedToSite),
    QuarantinedOnSite = query.Sum(q => q.QuarantinedOnSite)
};


If I understand it correctly, it'll execute the whole query 4 (5 if I count also counting but guess it's necessary) times so I tried to do optimize it to do everything in one step like this:

var result = new List<SimsSiteInventoryReportData>();
    var total = new SimsSiteInventoryReportData();
    
    foreach (var item in query)
    {
        total.QuantityOnSite += item.QuantityOnSite;
        total.QuantityDispatchedToSite += item.QuantityDispatchedToSite;
        total.QuarantinedOnSite += item.QuarantinedOnSite;
        result.Add(item);
    };
but according the Network in Chrome this optimalization is even a bit slower and I cant understand why. Any explanation ? Thanks
Was this page helpful?