I did a small experiment to test whether lamdba expression can retrieve faster results than 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 drawback of lambda expression
Here I/O operation ( println ) is much slower than all possible overhead of calling lambda or creating an iterator. In general forEach might be slightly faster as it does everything inside the single method without creating the Iterator and calling hasNext and next (which is implicitly done by for-each loop).
Both yields the same result because query expressions are translated into their lambda expressions before they're compiled. So performance-wise, there's no difference whatsoever between the two.
Oracle claims that use of lambda expressions also improve the collection libraries making it easier to iterate through, filter, and extract data from a collection. In addition, new concurrency features improve performance in multicore environments.
From the above picture shows that Lambda expression is multiple times faster than the usual approach, as well it is memory efficient too. In the test application, both the simple and complex scenario can be tested using the combo box.
Technically your 2 approaches are not identical. There are a few differences such as the use of "OfType
" which is filtering the collection before continuing. You'd be better using "Cast<GridViewRow>()
" as you know each element is of type GridViewRow.
Also, do you really need the expense of the ToList()
at the end of the Linq statement as your linq query is now ready to iterate over and execute rather than having to convert back to a list?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With