views:

107

answers:

3

Hi all:

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.GetItems(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.

+6  A: 

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.

SLaks
A: 

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

Asad Butt
A: 

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

Paul Creasey