Performance issues that need to be paid attention to when using the LINQ summation method sum to calculate multiple elements in the Set

Source: Internet
Author: User

Raise Questions

This article uses the following examples to illustrate the problem. The following is the complete code of the instance.

//************************************** ********************* // Sum application sample code /// Author: may 3, May /// Date: //// http://blog.csdn.net/yl2isoft ////****************************** * ***************************** using system; using system. collections. generic; using system. diagnostics; using system. LINQ; namespace linqsumexp {class program {static void main (string [] ARGs) {console. writeline ("data preparation in progress, please wait... "); List <score> scorelist = createscorelist (); console. writeline ("running, please wait... "); stopwatch SW1 = new stopwatch (); sw1.start (); // ------------ code snippet 1 -------------------- start int mathscoresum1 = 0; int chinesescoresum1 = 0; int engishscoresum1 = 0; int physicsscoresum1 = 0; int chemistryscoresum1 = 0; int biologyscoresum1 = 0; foreach (VAR s in scorelist) {mathscoresum1 + = S. mathscore; chinesescoresum1 + = S. chinesescore; englishscoresum1 + = S. engishscore; physicsscoresum1 + = S. physicsscore; chemistryscoresum1 + = S. chemistryscore; biologyscoresum1 + = S. biologyscore;} // ------------ code snippet 1 ---------------------- end sw1.stop (); timespan ts1 = sw1.elapsed; console. writeline ("the execution time of code snippet 1 is:" + ts1.totalmilliseconds); stopwatch sw2 = new stopwatch (); sw2.start (); // ------------ code snippet 2 starting start int mathscoresum2 = 0; int chinesescoresum2 = 0; int englishscoresum2 = 0; int physicsscoresum2 = 0; int ending = 0; int biologyscoresum2 = 0; mathscoresum2 = scorelist. sum (IT => it. mathscore); chinesescoresum2 = scorelist. sum (IT => it. chinesescore); englishscoresum2 = scorelist. sum (IT => it. englishscore); physicsscoresum2 = scorelist. sum (IT => it. physicsscore); chemistryscoresum2 = scorelist. sum (IT => it. chemistryscore); biologyscoresum2 = scorelist. sum (IT => it. biologyscore); // ------------ code snippet 2 ---------------------- end sw2.stop (); timespan ts2 = sw2.elapsed; console. writeline ("the execution time of code snippet 2 is:" + ts2.totalmilliseconds);} static list <score> createscorelist () {list <score> scorelist = new list <score> (); random RD = new random (); For (INT I = 0; I <100; I ++) {score S = new score (); S. studentid = I; S. studentname = "S" + I. tostring (); S. mathscore = RD. next (1, 0,100); S. chinesescore = RD. next (1, 0,100); S. engishscore = RD. next (1, 0,100); S. physicsscore = RD. next (1, 0,100); S. chemistryscore = RD. next (1, 0,100); S. biologyscore = RD. next (0,100); scorelist. add (s) ;}return scorelist;} public class score {public int studentid {Get; set;} Public String studentname {Get; set;} public int mathscore {Get; set;} public int chinesescore {Get; set;} public int englishscore {Get; set;} public int physicsscore {Get; set;} public int chemistryscore {Get; set ;} public int biologyscore {Get; Set ;}}}
The instance first defines the score class and uses the score class to save the score of each course, the attributes include mathscore, chinesescore, englishscore, physicsscore, chemistryscore, and biologyscore to save the scores of mathematics, Chinese, English, physics, chemistry, and biology. Then, the createscorelist method generates a set of 100 score objects. Finally, code snippet 1 and code snippet 2 are used to calculate the sum of each course in the set. Among them, code snippet 1 sums the sum by traversing the set, in code snippet 2, the sum method of LINQ is used to achieve the sum. Obviously, both methods can complete the basic function of summation. However, in actual development, in addition to basic functions, many other things, such as performance, need to be considered. So here I will ask: Which method has better performance?

 

Answer announcement

Read the blackboard. (Oh, is it a black board)

 

Figure 1 program running result

From the execution results of the program, the performance of method 1 is better.

You may say that this conclusion cannot be drawn only once through the results, because of contingency.

In order for you to take it orally, I will continue to execute, execute, and then execute.
After more than N repeated tests (N), I found that method 1 consumes less time and method 1 has better performance than method 2.

To make our experiment more convincing, increase the data volume to 100000, to execute the program. The following is the experiment result:

  • 1000 times: Method 1--1.2628; Method 2--3.3205
  • 10000 times: Method 1--3.1866; Method 2--8.8877
  • 100000 times: Method 1--15.3749; Method 2--65.5758

Or is method 1 less time-consuming?

If you don't accept it, I can't help it. I believe it.

So why is this result?

 

Cause description

View the source code of the sum method of LINQ. The Code is as follows:

public static int Sum(this IEnumerable<int> source){    if (source == null)    {        throw Error.ArgumentNull("source");    }   int num = 0;    foreach (int num2 in source)   {        num += num2;    }    return num;}

Obviously, every time you call the Evaluate Method of LINQ, the set is traversed. Therefore, method 2 traverses the set five times, and method 1 only needs to traverse the set once, which is the reason.

Of course, the more fields that need to be summed, the larger the data size, the larger the performance gap between the two methods. In fact, this problem will be encountered in addition to the sum of the sum method of LINQ. This problem will also occur when other extension methods of LINQ are used. I hope you will pay attention to it later.

 

 

 

 

 

 

 

Performance issues that need to be paid attention to when using the LINQ summation method sum to calculate multiple elements in the Set

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.