C#_ deep understanding of deferred execution of LINQ

Source: Internet
Author: User
I. Introduction to LINQ

LINQ Query Trilogy: First, get the data source; Second, create the query; Third, execute the query.
second, the benefits of delayed queries

What is the benefit of delaying a query? Take a look at the following code:

private static void Main ()
        {
            var list = new list<int> ();
            var rd = new Random ();
            for (var i = 0 i < 100000000; i++)
            {
                var num = Rd. Next ( -10000000, 10000000);
                List.            ADD (num);
            }
Recordingtime (list);
}
private static void Recordingtime (ienumerable<int> list)
        {
            var watch = new stopwatch ();
            Watch. Start (); Start timing

            var nums1 = list. Where (n => n > 0);

            var nums2 = new list<int> ();
            foreach (var i in list)
            {
                if (i > 0)
                {
                    nums2.            ADD (i);
                }
            }
 Watch. Stop (); Stop timed
            var time = watch. Elapsedmilliseconds;
            Console.WriteLine ($ "time consuming: {time} milliseconds");
        }

You can compare the efficiency of NUM1 and num2, in 100 million of data, using LINQ to find positive numbers in a set takes only 2 milliseconds (which can have more than 10 milliseconds of error), and using common methods (traversal plus judgment) takes more than 2 seconds. Nearly 2000 times times more efficient.

Why is the efficiency of LINQ so fast?

This is because LINQ does only two things in the above code: 1, get the data source, 2, create the query, and use the common method not only do the two work, it has done more query work, so LINQ is very efficient to run here. third, delay execution what will be the impact of talking in code

var list = new List<int> {1, 2, 3, 4, 5, 6, 7};
            var enumlist = list. Where (x => x >-4);
            foreach (Var num in enumlist)
            {
                Console.WriteLine (num);
            }
            Console.WriteLine ("");
            List. ADD ( -1);
            foreach (Var num in enumlist)
            {
                Console.WriteLine (num);
            }
Here I go up and down the enumlist is the same set, although I have to traverse the first time to change the list, normally I go up and down two times to traverse the output of the content should be consistent, but the result is not necessarily.

Just mentioned that LINQ did only two jobs: 1, get the data source, 2, create the query. So when and where was the execution of the query executed? The answer is: When Enumlist is used, it will execute, that is to say, var enumlist = list in this code. Where (x => x >-4); This line of code was executed two times.    The first time to execute is the first time to traverse the enumlist, the second execution is the second time to traverse the enumlist (you can interrupt the point of observation). the principle of delaying execution continue to code

private static void Main ()
        {  var list = new List<int> {-1, 1, 2, 3, 4, 5};
            var list1 = Delay (list);
            foreach (Var num in list1)
            {
                Console.WriteLine (num);
            }
            List. ADD ( -3);
            List. ADD (7);
            Console.WriteLine ("");
            foreach (Var num in list1)
            {
                Console.WriteLine (num);
            }
}
private static ienumerable<int> Delay (ienumerable<int> list)
        {          
            foreach (var num in list)
            {
                if (num>0)
                {yield return num}}}
        
In fact, the principle of lazy execution of LINQ is simple, if you understand yield return, then you will understand that the two are actually the same principle.
You can see that this code is the same as the code running the above, when you hit the breakpoint in the var list1 = Delay (list), step debugging is not going to enter the Delay method, only when you go through the List1, it will execute the Delay method, And if you use several list1, it will perform several delay methods. The difference between yield return and returns is that it is "on demand", that is, when you use it, when it is returned to your value.
When it comes to delaying execution that might affect the outcome, when I use list1 more than once, delay this method is executed multiple times, and the efficiency of the program is very low.     Take a look at my test, 10,000 plastic data printed seven times. Yield return (simulated deferred execution):
Direct printing: Normal print runs even lower (because normal printing is printing all numbers, the delay method filters out negative numbers). From this, it can be seen that when the result of deferred execution is called multiple times, it does not affect the efficiency of the operation.
five, which LINQ query operators are deferred executionGo to the definition of the LINQ query operator look at this.
When the return value is Ienumerable<tsource>, Ienumerable<igrouping<tkey, tsource>>, and Iorderedenumerable<tsource >, LINQ is deferred for execution. In fact, the above three return value types implement the ienumerable<t> (public enumerator) interface, yield return value is ienumerable<t> When the return value of the LINQ query operator is above three types, the query is a deferred query and the others are executed immediately. Vi. How to avoid delayed executionYou can see that deferred execution has both benefits and implications, and how to avoid this effect when deferred execution affects your own program. Simply, convert the return value to a different type, the LINQ query operator contains the definition of the conversion operation: ToArray (convert to Array), todictionary (converted to dictionary), ToList (converted to a collection), You can use these conversion operations to convert deferred execution to immediate execution, and you can avoid the impact of deferred execution.
My first blog, beginners in C # less than 3 months, write a bad place please point out in the comments area, I will promptly amend.
Related Article

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.