SoFunction
Updated on 2025-03-06

How to improve performance by exporting data to excel in C#

1. To improve performance, we must first know where the time is

1. Database query,

2. Combine data into new collection loops to nest too much

2. How do we optimize?

1. Database query,

1》, Database Query: If the data volume is small, we can use temporary datatable and table query, but if the data is tens of millions of millions of data, it is not recommended to use continuous tables

So what should I do at this time?

2》At this time, we can choose to query the single table first, and then loop the other related data we want. What points should we pay attention to at this time?

3》Reduce database query! ! ! ! ! ! ! ! ! This is the point, so how to reduce it? The normal logic is as follows, but the data volume is very performance-consuming

foreach (var item in listST)
{
  var sModel= GetModel(); //If this method querys the database once every time, it will be very performance-consuming!  !  !  This causes the loop to be very slow!  , Instant cache usage will be very slow   = ;
}

4》We can change our thinking and optimize the following code:

List<Student> listST = new List<Student>();
List<int> listInt = new List<int>();
int g = 0;
foreach (var item in listST)
{
  //// We can choose to query every 2,000 data  ////Save as a collection  if (g % 2000 == 0)
  {
     listST = GetList($"id in ({(",", (g).Take(2000).Select(m => ).Distinct().ToArray())})", 2000, 1, "name,Id");
  }
  var sModel = (m =>  == );
   = ;
  g++;
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.