c# - Linq deferred operations -


i understand deferred execution, have question particular case:

given code fragment such as

                        var resultsofinterest = r in ...                                                 select r;                         foreach (var x in resultsofinterest)                         {                             //do x                         } 

how many times query resultsofinterest executed? once when setting foreach loop, or once every element 'x'? more efficient

                        foreach (var x in resultsofinterest.toarray())                         {                             //do x                         } 

?

tia

in both cases, runs once.

in first example, (if linq-to-objects query), runs long enough next x on each iteration. in second example, has evaluates entire result set @ once , stores array.

so, suppose expensive query , takes 1 second each item, , there 20 items in list, both queries take 20 seconds process items. however, first 1 blocked 1 second on each iteration while gets next item, second blocked 20 seconds before start of loop, loops through items in array quickly.

neither more efficient in when comes evaluating query. in general, however, should avoid unnecessary calls toarray or tolist, since in addition evaluating query, must allocate array results (list<t> stores items in internal array). list of 20 items, doesn't mean much, when have several thousand items, can cause noticeable slow-down. of course, doesn't mean toarray always bad. if had 5 foreach-loops in previous example, storing results in array , looping through array rather re-evaluating query each time speed code 80 seconds


Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

IIS->Tomcat Redirect: multiple worker with default -