开发者

Lambda expression is slower than foreach statement?

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.FindCont开发者_Python百科rol("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


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?


There is a small overhead with lambda expressions because they are "compiled" at runtime. I think that's what you see in your "benchmark". for each ... is a fully compiled statement.

You can precompile lambda expressions. Look here. Maybe you want to rework your code and test again.


I won't talk about the correctness of your code but I'd like to get a chance to explain a general rule In Software Develpment the performance loss is inversely proportional to the level of abtsraction. In this case in quite normal that foreach is faster then LINQ (which is more abstract). If you compare it with the classic for (for (int i:i++l,etc..) ) it will be faster than the foreach. Access an object thought an interface is slower then access the concrete object : the interface is already a very small level of abstraction. The code you write will be as much fast as it is "close" to the machine language but of course it will be less readable and maintainable. The matter is how to find the right level of abstraction for what we are developing keeping an eyes on the performance and the code readability.

You won't need MVC pattern for making a one-page web site that shows a table on a Repeater :-)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜