157 recommendations for writing high-quality code to improve C # programs--Recommendation 28: Understanding the difference between deferred evaluation and active evaluation

Source: Internet
Author: User

Recommendation 28: Understanding the difference between deferred evaluation and active evaluation

To understand the delay evaluation (lazy evaluation) and the active evaluation (eager evaluation), let's look at an example:

list<int> list =Newlist<int> () {0,1,2,3,4,5,6,7,8,9 }; varTemp1 = fromCinchListwhereC >5 SelectC; varTemp2 = ( fromCinchListwhereC >5 Selectc). tolist<int>(); list[0] = One; Console.Write ("Temp1:"); foreach(varIteminchTemp1) {Console.Write (item+" "); } console.write ("\NTEMP2:"); foreach(varIteminchTemp2) {Console.Write (item+" "); }

Output:

Temp1:11 6 7 8 9
Temp2:6 7 8 9

In the case of a delayed job search, only one query is defined, not executed immediately. Access to the results of the query iterates through the original collection each time. As in the previous iteration of TEMP1, we modified the value of list[0] before the iteration, so that the modification directly affected the output of the iteration. Calls to the query ToList, ToArray, and so on, will be made immediately, because the changes to list[0] are made after the TEMP2 query, so the changes to list[0] will not affect the results of TEMP2.

Latency evaluation can lead to significant performance gains when using LINQ to SQL. For example, if two queries are defined and deferred evaluation is used, the CLR merges two queries and generates a final query:

        Static voidMain (string[] args) {DataContext CTX=NewDataContext ("server=192.168.0.102;database=temp;uid=sa;pwd=sa123"); Table<Person> persons = CTX. Gettable<person>(); varTemp1 = fromPinchPersonswhereP.age > - Selectp; //omitted            varTemp2 = fromPinchTemp1whereP.name.indexof ('e') >0 Selectp; foreach(varIteminchTemp2) {Console.WriteLine (string. Format ("Name:{0}\tage:{1}", item. Name, item.            Age)); }} [Table (Name=" Person")]        classPerson {[Column] Public stringName {Get;Set; } [Column] Public intAge {Get;Set; } }

Note: This code requires support for the SQL Server database. This code assumes that there is already a temp database with a person table with two fields in the table:

Name, varchar (50)

Age, int

At the beginning of the iteration, the LINQ to SQL engine generates the following SQL query statement:

exec sp_executesql N ' SELECT [t0]. [Name], [t0]. [Age]

From [person] as [t0]

WHERE (

(case

When (datalength (@p0)/2) = 0 Then CONVERT (bigint,0)

ELSE Convert (BigInt, (CONVERT (Int,charindex (@p0, [t0].[ Name]))-1)

END) > @p1) and ([t0].[ Age]> @p2) ', N ' @p0 nchar (1), @p1 int, @p2 int ', @p0 =n ' e ', @p1 =0, @p2 =20

The final SQL statement incorporates queries for age and name criteria.

If the values in the person table are as follows:

According to the above query will return:

Name:steve age:21

Name:jessica age:22

If an active evaluation is used:

            var temp1 = (from inwhereSelect p). Tolist<person>();             // omitted            var  from inch where p.name.indexof ('e'0select p;

The following statement is generated:

exec sp_executesql N ' SELECT [t0]. [Name], [to]. [Age]

From [person] as [t0]

WHERE [T0]. [age]> @p0 ', N ' @p0 int ', @p0 =20

The database will return 3 data

Name:steve age:21

Name:jessica age:22

Name:lisa age:23

Although the results returned by the TEMP2 query are also two records, the query for Temp2 is actually a filter for 3 data that has been returned to the local. In this example, the efficiency problem of returning 3 or 2 is not obvious, but putting the application in the Internet system and reducing the amount of traffic in each place will give us a significant performance boost.

In fact, the difference between the delay evaluation and the active evaluation should be carefully understood, and the results will be realized in the application: otherwise, there will be some unexpected bugs.

Turn from: 157 recommendations for writing high-quality code to improve C # programs Minjia

157 recommendations for writing high-quality code to improve C # programs--Recommendation 28: Understanding the difference between deferred evaluation and active evaluation

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.