Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# laziness question

Tags:

c#

linq

What's the common approach to design applications, which strongly rely on lazy evaluation in C# (LINQ, IEnumerable, IQueryable, ...)?

Right now I usually attempt to make every query as lazy as possible, using yield return and LINQ queries, but in runtime this could usually lead to "too lazy" behavior, when every query gets builts from it's beginning obviously resulting in severe visual performance degradation.

What I usually do means putting ToList() projection operators somewhere to cache the data, but I suspect this approach might be incorrect.

What's the appropriate / common ways to design this sort of applications from the very beginning?

like image 877
Yippie-Ki-Yay Avatar asked Apr 12 '11 11:04

Yippie-Ki-Yay


2 Answers

I find it useful to classify each IEnumerable into one of three categories.

  1. fast ones - e.g. lists and arrays
  2. slow ones - e.g. database queries or heavy calculations
  3. non-deterministic ones - e.g. list.Select(x => new { ... })

For category 1, I tend keep the concrete type when appropriate, arrays or IList etc. For category 3, those are best to keep local within a method, to avoid hard-to find bugs. Then we have category 2, and as always when optimizing performance, measure first to find the bottlenecks.

like image 87
Felix Ungman Avatar answered Oct 12 '22 22:10

Felix Ungman


A few random thoughts - as the question itself is loosely defined:

  • Lazy is good only when the result might not be used hence loaded only when needed. Most operations, however, would need the data to be loaded so laziness is not good in that term.
  • Laziness can cause difficult bugs. We have seen it all with data contexts in ORMs
  • Lazy is good when it comes to MEF
like image 28
Aliostad Avatar answered Oct 13 '22 00:10

Aliostad