© 2026 Hedgehog Software, LLC

TwitterGitHubDiscord
More
CommunitiesDocsAboutTermsPrivacy
Search
Star
Setup for Free
C#C
C#•2y ago•
31 replies
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)
};
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);
    };
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
C# banner
C#Join
We are a programming server aimed at coders discussing everything related to C# (CSharp) and .NET.
61,871Members
Resources

Similar Threads

Was this page helpful?
Recent Announcements

Similar Threads

❔ QuestionController
C#CC# / help
3y ago
Visual Studio C# WinForms, a question for better performance.
C#CC# / help
2y ago
Performance Optimization
C#CC# / help
3w ago