Home > other >  How can I optimize the following code faster?
How can I optimize the following code faster?

Time:03-06

I have two list:

reports count 6000 and invoices count 6000

I have loop like this:

foreach (var item in reports) 
{
    item.SettlementProcessStatus =
        invoices.Any(t => t.InvoiceId == item.RelatedInvoiceId) 
           ? SettlementProcessStatus.Done 
           : SettlementProcessStatus.Error;
}

At first, this code has a good speed, but the higher the index, the slower it becomes. what solutions are recommended to optimize it?

CodePudding user response:

The performance problem is that your code has to iterate at least partially through invoices for each of your reports. To avoid this, first create a HashSet with all your invoice ID's and then search in there instead of your list.

Assuming you have integer ID's you could do:

var invoiceIds = new HasSet<int>(invoices.Select(x => x.InvoiceId));

foreach (var item in reports) 
    item.SettlementProcessStatus = invoiceIds.Contains(item.RelatedInvoiceId) ?
        SettlementProcessStatus.Done :
        SettlementProcessStatus.Error;

CodePudding user response:

Instead of using a list for invoices, use a dictionary that have the RelatedInvoiceId as its Key Value.

That avoids iterating trough all list items each item.

  • Related