Is a lambda expression slower than a foreach expression?

I did a little experiment to check if the lamdba expression can get a faster result than the foreach statement. but, lambda failed

System.Diagnostics.Stopwatch st = new System.Diagnostics.Stopwatch(); st.Start(); List<int> lst = new List<int>(); foreach (GridViewRow item in GridView1.Rows) { if (((CheckBox)item.FindControl("Check")).Checked) { lst.Add(Convert.ToInt32(((Label)item.FindControl("Id")).Text)); } } st.Stop(); Response.Write(st.Elapsed.ToString()); Response.Write("<br/><br/><br/>"); st.Reset(); st.Start(); List<int> lstRank = GridView1.Rows.OfType<GridViewRow>().Where(s => ((CheckBox)s.FindControl("Check")).Checked) .Select(s => Convert.ToInt32(((Label)s.FindControl("Id")).Text)).ToList(); st.Stop(); Response.Write(st.Elapsed.ToString()); int i = 0; output 00:00:00.0000249 00:00:00.0002464 

why lambda is slower than foreach. This may be a disadvantage of the lambda expression.

+6
linq
source share
3 answers

Technically, your 2 approaches are not identical. There are several differences, such as using " OfType ", which filters the collection before continuing. You are better off using " Cast<GridViewRow>() " since you know that each element is of type GridViewRow.

Also, do you really need the ToList() expense at the end of the Linq statement, since your linq query is now ready to be repeated and executed, and not converted back to a list?

+3
source share

There is little overhead with lambda expressions because they are "compiled" at runtime. I think what you see in your benchmark. for everyone ... this is a fully compiled statement.

You can precompile lambda expressions. Take a look here . Perhaps you want to rework your code and test it again.

+2
source share

I will not talk about the correctness of your code, but I would like to be able to explain the general rule In Software Develpment, performance loss is inversely related to the level of abstraction. In this case, it’s quite normal that foreach is faster than LINQ (which is more abstract). If you compare it with the classics for (for (int i: i ++ l, etc.)), it will be faster than foreach. Access to an object assumes that the interface is slower than access to a specific object: the interface is already a very small level of abstraction. The code you write will be as fast as "close" to machine code, but, of course, it will be less readable and convenient. The point is how to find the right level of abstraction for what we are developing, taking into account the performance and readability of the code.

You do not need an MVC template to create a one-page website that shows a table on a repeater :-)

+2
source share

All Articles