C# 4 attention questions to improve efficiency of loop

Lionsure 2020-07-21 Original by the website

It is common to use loops in the process of programming; if the number of loops is small, the performance difference is not obvious; on the contrary, if the loops are 1 million times, 10 million times, or even more, the performance difference will be very obvious in time Obviously, it could be executed in tens of milliseconds, but it took hundreds of milliseconds or more. Therefore, usually writing programs pay more attention to accumulating knowledge of performance and efficiency, and the advantages at the critical moment are reflected. So what issues should be paid attention to to improve efficiency of loop?

 

For example, the classes to be used are as follows:

//User class
       public class UserInfo
       {
              string userName;
              string address;
              int age;
       }

 

C# 4 attention questions to improve efficiency of loop

1. Avoid declaring variables in loops, especially declaring objects

Inefficient:

for (int i = 0; i < 100000; i++)
       {
              UserInfo uObj = new UserInfo();
              if(uObj.userName == "Jolen")
              {
              }
       }

Efficient:

UserInfo uObj = new UserInfo();
       for (int i = 0; i < 100000; i++)
  {
              if(uObj.userName == "Jolen")
              {
              }
       }

Tip: Creating an object consumes a lot of system resources. If you create the object repeatedly in the loop, the system performance will be greatly reduced, so try to avoid creating objects.

 

2. Avoid double counting the total number of elements in the collection

IList lst = new List();

Inefficient:

for (int i = 0; i < list.count; i++)
       {
              if(lst[i].userName == "Jolen")
              {
              }
       }

Efficient:

int lth = list.count;
       for (int i = 0; i < lth; i++)
       {
              if(uObj.userName == "Jolen")
              {
              }
       }

3. for is a bit more efficient than foreach. If you can use for, don't use foreach. In the article "C# foreach vs for performance", we will use examples to compare their efficiency.

4. If you can use loops instead of recursive calls, don't use recursive calls. Recursion is less efficient. In addition, try to minimize loop nesting, which will seriously reduce efficiency.