Slow foreach() on a LINQ query - ToList() boosts performance immensely - why is this?

前端 未结 3 1813
猫巷女王i
猫巷女王i 2021-01-04 07:59

I kind of grasp the whole delayed execution concept, but the following has me puzzled...

On a DataTable containing about 1000 rows, I call AsEnumerable(). I

相关标签:
3条回答
  • 2021-01-04 08:12

    Indeed you seem to have no clear idea what is execution of code and what is definition of the intent to (possibly) execute later when the results are actually used. I suggest reading up one this part of LINQ.

    And possibly try executing both of your variants with a debugger attached so you can actually see what code is executing in which order and what is actually happening to your data. You might be in for a (big?) surprise here...

    0 讨论(0)
  • 2021-01-04 08:15

    You don't understand which methods are deferred and which are not, so you don't understand when your code defines operations vs performs operations.

    These are all deferred. They define, but do not execute, an operation.

    source.AsEnumerable
    source.Select
    source.Where
    

    These enumerate the source and so are not deferred.

    source.ToList
    source.First
    source.Single
    foreach(var x in source)
    
    0 讨论(0)
  • 2021-01-04 08:25

    It will not get all items from database until you type

     ToList or First or Single
    

    In foreach, you send a query into database for each item. So it works slower. Open your sql profiler to understand better.

    0 讨论(0)
提交回复
热议问题