Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 283
BeraCim Avatar asked Feb 24 '10 00:02

BeraCim


1 Answers

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.

like image 174
SLaks Avatar answered Nov 13 '22 00:11

SLaks