开发者

Efficiency of putting a query in the C# foreach condition

I came across this c# code in a project today and I couldn't help but question its efficiency:

SPList spList = spWeb.GetListCustom("tasks");
foreach (SPListITem item in spList.Get开发者_StackOverflowItems(query))
{
    //... do something with the SPListCollection it returned
}

Being from a Java background, the spList.GetItems(query) definitely made me think that its a performance hit. I would've done something like the following to improve it:

SPList spList = spWeb.GetListCustom("tasks");
SPListIteCollection taskListCollection = taskList.GetItems(query);
foreach (SPListITem item in taskListCollection)
{
    //... do something with the SPListCollection it returned
}

However, the code is in C#...

So my question is: would the code I suggested above improve performance, or have I missed something fundamental about C#'s foreach loop?

Thanks.


The two blocks of code are completely identical, and will compile to the exact same IL in Release mode.

Unlike a regular for loop, a foreach loop will only use the collection once (to call GetEnumerator). Therefore, you have nothing to worry about.


the enumerator in the foreach is only evaluated once, works the same in java too.


Second code block is just clearer to read, not other benefits. I could understand better that the foreach is playing with SPListIteCollection.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜