Comparison of the Performance of a Group using the LinQ to SQL and non-LinQ methods.
A data table with 476550 data records. Group A field and sort it by the field. This requirement is implemented by using the methods of LinQ to SQL and non-LinQ respectively, and then let's take a look at the performance comparison.
LinQ way
From p in context. Part_Partgroup p by p. FunctionGroup into groupedPsorderby groupedPs. Keyselect groupedPsLinQ way for group
Non-LinQ way
Var results = new SortedDictionary <long ?, IList <Part_Part> (); foreach (var p in context. Part_Part) {IList <Part_Part> groupedValue = null; if (! Results. tryGetValue (p. functionGroup, out groupedValue) {groupedValue = new List <Part_Part> (); results [p. functionGroup] = groupedValue;} groupedValue. add (p );}Non-LinQ way for group
Slave
var results = new SortedDictionary<long?, IList<Part_Part>>();
We can see that the field type used for sorting is long ?. Let's take a look at the execution time.
|
LinQ Way |
Non-LinQ Way |
First time |
. 698 |
6.707 |
Second time |
. 404 |
1.426 |
Third time |
. 127 |
1.486 |
Forth time |
. 952 |
1.425 |
Obviously, under scenario, the performance of LinQ is very low. Adjust the Code. This time, the PartDescription Group of the string type is used. Test results.
|
LinQ Way |
Non-LinQ way |
First time |
> 30 min |
8.738 |
Second time |
> 30 min |
4.201 |
Third time |
> 30 min |
4.173 |
Forth time |
> 30 min |
4.176 |
In this scenario, the time consumption of non-LinQ way is increased, while that of LinQ way is even worse. Even after waiting for 30 minutes, the test program was terminated early.
It can be seen that, in addition to simplicity and excellent readability, LinQ also results in performance loss. Let's take a look at the description of the LinQ performance issue in "LinQ in Action.
There are no surprises. LINQ does not come for free. LINQ queries cause additional work, object creations, and pressure on the garbage collector. the additional cost of using LINQ can vary a lot depending on the query. it can be as low as 5 percent, but can sometimes be around 500 percent.
In this case, can we still enjoy using LinQ in the future? Let's take a look at the description in "LinQ in Action.
Do not be afraid to use LINQ, but use it wisely. for simple operations that are executed extensively in your code, you may consider using the traditional alternatives. for simple filter or search operations, you can stick to the methods offered by List <T> and arrays, such as FindAll, ForEach, Find, ConvertAll, or TrueForAll. of course, you can continue to use the classic for and foreach statements wherever LINQ wocould be overkill. for queries that are not executed several times per second, you can probably use LINQ to Objects safely. A query that is executed only once in a non-time-critical context won't make a big difference if it takes 60 milliseconds to execute instead of 10.