c# - "Nested foreach" vs "lambda/linq query" performance(LINQ-to-Objects) -


Why should you use "nested forehack" or "lambda / linux query" in the display point?

You can type clear code, and then find the benchmark and profile any performance issues If you have performance problems in do , you can experiment with a different code to decide whether it is fast or not (measuring all the time as possible as realistic data ) And then make a decision call whether the performance improves the readability hit. Is necessary.

A direct foreach approach will be faster than LINQ in many cases. For example, consider:

  var query = From the element in the list where element.x> 2 where element.Y & lt; Select 2 elements. X + element why; Foreach (var value in query) {Console.WriteLine (value); }  

Now there are two where section and a select section, so every last object has to go through three walks . (Apparently where two cases can be added in this case, but I am making a general point.)

Now compare it directly to the code:

  foreach (Var element in list) {if (element.X> gt; 2 & amp; amp; amp; element; y & lt; 2} {Console.WriteLine (element.X + element.Y); }}  

This will run faster, because there are less hoops for running it's likely that the console output will be dwarf in the Iterator cost, though, and I would definitely like the LINQ query .

EDIT: To answer about "nested forward" loops ... usually they select multiple or a << code> to section:

  var query = Item from nested item first whiteness in the item. Items Select Items Basecount + nested item. Nested;  

Here we are only adding an additional Iterator, because we were already using an additional error in the first sequence due to nested foreach loop. There is still a little overhead, which includes an overhead to launch in a representative instead of "Inline" (which I had not mentioned earlier), but it will still not be very different for Nested-Exotic display.

Not to say that you can not shoot yourself in the foot with LINQ, of course. If you do not include your brain first, then you can write stupidly disabled questions - but it is far from unique LINQ ...


Comments

Popular posts from this blog

c++ - Linux and clipboard -

What is expire header and how to achive them in ASP.NET and PHP? -

sql server - How can I determine which of my SQL 2005 statistics are unused? -